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

查看:66
本文介绍了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 ,服务器有责任发送状态为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天全站免登陆