Html Angular 2 中的访问控制允许 Origin 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41683195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access Control Allow Origin issue in Angular 2
提问by Michal Bialek
I have a problem with getting data from my node.js server.
我在从 node.js 服务器获取数据时遇到问题。
The client side is:
客户端是:
public getTestLines() : Observable<TestLine[]> {
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://localhost:3003/get_testlines', options)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
in server side I also set the headers:
在服务器端,我还设置了标题:
resp.setHeader('Access-Control-Allow-Origin','*')
resp.send(JSON.stringify(results))
But I get an error
但我收到一个错误
"XMLHttpRequest cannot load http://localhost:3003/get_testlines. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access."
“XMLHttpRequest 无法加载http://localhost:3003/get_testlines。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。Origin' http:// localhost:3000' 因此不允许访问。”
How can I fix it? When I remove headers it says that this header is required.
我该如何解决?当我删除标题时,它说这个标题是必需的。
采纳答案by Quentin
Access-Control-Allow-Origin
is a responseheader, not a request header.
Access-Control-Allow-Origin
是响应头,而不是请求头。
You need to have it appear on the response, not the request.
你需要让它出现在响应中,而不是请求中。
You have attempted to put it on the response:
您已尝试将其放在响应中:
resp.setHeader('Access-Control-Allow-Origin','*')
resp.setHeader('Access-Control-Allow-Origin','*')
… but it hasn't worked.
......但它没有奏效。
This is probably because you haven't put it on the response to the right request. The error message says:
这可能是因为您没有将其放在对正确请求的响应中。错误消息说:
Response to preflight requestdoesn't pass access control check
对预检请求的响应未通过访问控制检查
You have done somethingto make the request preflighted. This means that before the browser makes the GET request you are trying to make, it is making an OPTIONS request.
您已经做了一些事情来预检请求。这意味着在浏览器发出您尝试发出的 GET 请求之前,它正在发出一个 OPTIONS 请求。
This is, presumably, being handled by a different piece of code on your server so the line resp.setHeader('Access-Control-Allow-Origin','*')
isn't being hit.
这大概是由服务器上的不同代码段处理的,因此该行resp.setHeader('Access-Control-Allow-Origin','*')
不会被击中。
One thing that causes a preflighted request to be made is the addition of request headers (other than a small number of exceptions). Adding Access-Control-Allow-Origin
to the requestwill trigger a preflighted request, so the first thing to do to try to fix the problem is to remove Access-Control-Allow-Origin
from the request.
导致发出预检请求的一件事是添加请求标头(少数例外除外)。添加Access-Control-Allow-Origin
到请求将触发预检请求,因此尝试解决问题的第一件事是从请求中删除Access-Control-Allow-Origin
。
If that fails, then you need to set up your server so it can respond to the OPTIONS request as well as the GET request.
如果失败,那么您需要设置您的服务器,以便它可以响应 OPTIONS 请求以及 GET 请求。
回答by Bettaibi Nidhal
Access-Control-Allow-Origin is a response header, not a request headeryou need to fix the permission in your backend. so you must create cors.js file that contains all necessary permissions.
Access-Control-Allow-Origin 是一个响应标头,而不是 您在后端修复权限所需的请求标头。因此您必须创建包含所有必要权限的 cors.js 文件。
function crosPermission(){
this.permission=function(req,res,next){
res.header('Access-Control-Allow-Origin','*');
res.header('Access-Control-Allow-Headers','Content-Type');
res.header('Access-Control-Allow-Methods','GET','POST','PUT','DELETE','OPTIONS');
next();
}
}
module.exports= new crosPermission();
next stepYou need to add some line in your app.js
下一步您需要在 app.js 中添加一些行
var cors=require('./cors');
app.use(cors.permission)
回答by Mezo Istvan
Don't set Access-Control-Allow-Origin
on the request, it is never needed there. You should double-check if the header is present on the response (check it in the developer console). It would be helpful if you shared more of the backend code.
不要设置Access-Control-Allow-Origin
请求,那里永远不需要它。您应该仔细检查响应中是否存在标头(在开发人员控制台中检查)。如果您共享更多后端代码,将会很有帮助。
回答by aabbcc
If this is going to be rest API => http://localhost:3003/get_testlines
如果这将是休息 API => http://localhost:3003/get_testlines
then use @CrossOrigin(origins = "*") to solve the cross domain issue
然后使用@CrossOrigin(origins = "*") 解决跨域问题
回答by AmirReza-Farahlagha
This has nothing to do with the client. Very simply you can solve this problem by adding Cors to the Configure method. like this:
这与客户端无关。很简单,您可以通过将 Cors 添加到 Configure 方法来解决此问题。像这样:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
InitializeDatabase(app);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMiddleware<ExceptionToResultMiddleware>();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseCors(s => s.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); ==> This section
app.UseMvc();
}
Now Restart your project and check again.
现在重新启动您的项目并再次检查。