对后端API的Angular客户端请求无法通过访问控制检查

时间:2018-06-06 11:03:13

标签: angular asp.net-core cors

我有一个角度6客户端,它将请求发送到单独的ASP.NET Core API,并在 startup.cs 文件中进行以下配置:

配置服务方法中的

services.AddCors(options =>
{
    options.AddPolicy(
        "MyPolicy",
        builder =>
        {
            builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
        });
});
配置方法

// called before UseMvc
app.UseCors("MyPolicy");

在本地测试时,通话正常。当在测试机器上部署并通过它的ip和端口访问角度客户端时,请求给出:

Failed to load http://xxxIPxx:xxxPortxxx/xxxURLxxx:  Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.  Origin 'http://xxxIPxx:xxxPortxxx' is therefore not allowed
access. The response had HTTP status code 502.

(这是Google Chrome显示的错误消息)

我可以错过什么?

1 个答案:

答案 0 :(得分:0)

在从Angular应用程序发出请求时,您应该包含Access-Control-Allow-Origin标头。

axios的简单示例: 从' axios&#39 ;;

导入axios
const Http = axios.create({
  baseURL: 'https://example.com/api',
  headers: { 'Access-Control-Allow-Origin': '*' }
});

export default Http;