Angular2 到 REST WebApi CORS 问题 [英] Angular2 to REST WebApi CORS issue

查看:20
本文介绍了Angular2 到 REST WebApi CORS 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angular2 前端和 WebApi 后端.webapi 启用了 CORS

I'm using an angular2 front end and WebApi backend. The webapi is CORS enabled

var cors = new EnableCorsAttribute("*", "*", "*");
GlobalConfiguration.Configuration.EnableCors(cors);

它可以工作,因为我有不同的网站(jQuery/Javascript)使用这个 api.但是对于 angular2 它没有.我收到以下消息:

and it works, because I have different sites (jQuery/Javascript) that use this api. But with angular2 it doesn't. I get the following message:

对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin"标头.

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

也许与预检请求"有关?

Maybe is something related to "preflight request" ?

推荐答案

我在 Angular2 应用程序中遇到了同样的问题.如前所述,问题在于,在客户端发出的每个请求之前,预检请求都会发送到服务器.

I had the same issue in my Angular2 application. The problem, as already stated, is that before every request made by the client a preflight request is sent to the server.

这种类型的请求有一个 OPTIONS 类型,服务器有责任发回 preflight 响应,状态为 200,并且标头设置为接受来自该客户端的请求.

This kind of request have a type OPTIONS, and it's duty of the server to send back a preflight response with status 200 and headers set for accepting requests from that client.

这是我的解决方案(带快递):

This is my solution (with express):

// Domain you wish to allow
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'YOUR-CUSTOM-HEADERS-HERE');

// Set to true if you need the website to include cookies in  requests
res.setHeader('Access-Control-Allow-Credentials', true);

// Check if preflight request
if (req.method === 'OPTIONS') {
    res.status(200);
    res.end();
}
else {
    // Pass to next layer of middleware
    next();
}

如您所见,如果请求类型为 OPTIONS,我设置了标头然后获取.在这种情况下,我发回状态 200 并结束响应.

As you can see, i set the headers and then fetch if the request type is OPTIONS. In that case i send back a status 200 and end the response.

通过这种方式,客户端将获得授权,您还可以在所有请求中设置自定义标头.

In this way, the client will be authorized and you will be also able to set your custom headers in all the requests.

这篇关于Angular2 到 REST WebApi CORS 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆