Access-Control-Allow_Headers CORS在通过Axios从Javascript代码发布到.net WebApi时出错
我正在使用Axios执行一个从javascript到.NETWebAPI的post请求。我将以下代码添加到我的WebApi的Startup.cs中,以允许任何头并接受来自localhost的流量,如下所示: Startup.cs配置服务Access-Control-Allow_Headers CORS在通过Axios从Javascript代码发布到.net WebApi时出错,javascript,asp.net-core,axios,cors,asp.net-core-webapi,Javascript,Asp.net Core,Axios,Cors,Asp.net Core Webapi,我正在使用Axios执行一个从javascript到.NETWebAPI的post请求。我将以下代码添加到我的WebApi的Startup.cs中,以允许任何头并接受来自localhost的流量,如下所示: Startup.cs配置服务 servies.AddCors(options => { options.AddPolicy("AllowPolicy", builder => builder .Wit
servies.AddCors(options =>
{
options.AddPolicy("AllowPolicy",
builder => builder
.WithOrigins("http://localhost:8081")
.AllowAnyHeader());
});
控制器的操作用“EnableCors”属性修饰以应用上述策略
[HttpPost]
[Route("customers/{tenantNumber}")]
[EnableCors("AllowPolicy")
public async Task<ActionResult> AddCustomer(Customer customer){
}
返回以下消息:“从origina“本地主机客户端站点”访问“webApi站点”上的XMLHttpRequest已被CORS策略阻止:飞行前响应中的访问控制允许标头不允许请求标头字段内容类型”
我尝试删除内容类型头并将类型更改为“application/x-www-form-urlencoded”,但似乎无法跟踪此错误
有人能告诉我我错过了什么吗?我已经尝试过这里提到的许多解决方案,但似乎可以解决这个问题。尝试保持axios实例创建的简单性,并在请求中提供类似
头文件
作为配置
参数,例如:
const custAPI = axios.create();
// Send request
const options = {
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
};
const result = await custAPI.post(fullUrl, customer, options);
请注意,您发布的代码存在多个语法错误,缺少引号,并试图将
custAPI
用作函数而不是对象。关键是“飞行前响应”。浏览器使用OPTIONS方法发出请求,因此您需要将其添加到服务器端代码中代码>在启动中?示例:@juunas….抱歉,没有包含该内容,但是的,我将其添加到了Configure方法中。.AllowAnyMethod()
@hereticsmonkey。。。您是否建议创建扩展方法、属性等。。?你能分享一下你所说的代码片段吗?我正在使用.NETCore3.1
const custAPI = axios.create();
// Send request
const options = {
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
};
const result = await custAPI.post(fullUrl, customer, options);