const formData = new FormData();
formData.append("CustomerName", this.state.customerName);
formData.append("Email", this.state.email);
formData.append("Phone", this.state.phone);
formData.append("PageNumber", this.state.pagesNumber);
formData.append("Notes", this.state.notes);
formData.append("WritingConversionTypeId", this.state.writingConversionTypeId);
formData.append("WritingDocumentTypeId", this.state.writingDocumentTypeId);
formData.append("WritingTimePeriodId", this.state.writingTimePeriodId);
formData.append("files", 'null');
writingRequest.postwritingRequest(formData).then((res) => {
console.log(res);
});
当附加到headrs表单数据时,它返回CORS,我使用react.js和服务器端ASP.NET Core3.1.当从标题中移除(内容-类型:多部分/表单-数据)时,它可以工作在swagger中。
在……里面
at React Service to Call Api
import http from "../../config/http";
import endPoints from "../endPoints";
const writingRequestUrl = endPoints.WRITING_REQUEST_ENDPOINT;
export default {
postwritingRequest(writingRequest) {
return http
.post(
writingRequestUrl,
writingRequest
, {
headers: {
'enctype': 'multipart/form-data',
"Content-Type": "multipart/form-data"
},
}
)
.then((res) => {
return res;
});
},
};
In StartUp
At ASP.NET CORE
ConfigureServices
//Enable CROS To allow access to the resource
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
}));
In Configure
app.UseCors("MyPolicy");
发布于 2020-09-24 01:09:11
CORS与react无关,当客户端运行在与服务器不同的域时,浏览器会阻止调用。在生产中,这通常不是一个问题,因为两者通常都运行在同一个域上。
如果您想在开发中避免CORS,附带了一个代理服务器,它将CORS头附加到所有请求中,如文档中所述。
只需将URL添加到package.json
中,如下所示:
"proxy": "www.url-to-your-api.com"
然后,确保对绝对链接运行来自您的react应用程序的所有请求,因此,与其调用www.url-to-your-api.com/api/
,不如简单地使用/api/
,这将在开发中使用代理,在生产中使用常规路径。
https://stackoverflow.com/questions/64042792
复制相似问题