为什么上传文件时react.js会返回cors



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);
});

当附加到heads表单数据时,它返回CORS我使用的是react.js和服务器端ASP.NET Core3.1。。。它在从标头中删除(内容类型:多部分/表单数据(时起作用它在招摇中工作

在此处输入图像描述

在中

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");

CORS与react无关,因为客户端运行在与服务器不同的域上,所以浏览器会阻止调用。在生产中,这通常不是问题,因为两者通常都在同一个域上运行。

如果您想在开发中避免CORS,Create React App捆绑包附带一个代理服务器,它会将CORS头附加到所有HTTP请求中,如文档中所述。

只需将api的URL添加到package.json中,如下所示:

"proxy": "www.url-to-your-api.com"

然后,请确保根据绝对链接运行来自react应用程序的所有请求,因此,与其调用www.url-to-your-api.com/api/,不如简单地使用/api/,这将在开发中使用代理,在生产中使用常规路由。

最新更新