[英]Cross orgin error in google chrome for the api call
in the nodejs backend i have added this code to the server.js 在nodejs后端中,我已将此代码添加到server.js
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
but in angularjs 2 client side in google chrome is throwing this error 但是在谷歌浏览器的angularjs 2客户端中抛出此错误
XMLHttpRequest cannot load http://localhost:8080/team. 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. The response had HTTP status code 405.
this is the service code for angular2 i'm using 这是我正在使用的angular2的服务代码
export class DataService {
// URL to web api
constructor(private http: Http, private _configuration: Configuration,private team:Team) {
//this.actionUrl = _configuration.ServerWithApiUrl;
this.actionUrl = "http://localhost:8080/team";
}
private actionUrl: string;
addData(postData: Team): Observable<Team[]> {
//let body = JSON.stringify({ Team });
this.team = postData;
console.log(this.team);
let body = JSON.stringify({ postData });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(body);
return this.http.post(this.actionUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
UPDATED: 更新:
For your new error message: Angular2 is lower-casing the headers. 对于您的新错误消息:Angular2使用较低的标题框。 Please update your backend to accept
content-type
too. 请也更新您的后端以接受
content-type
。
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, content-type, Accept");
You cant test post's to this URL: http://posttestserver.com/post.php?dir=anyNameYouWillFind 您无法测试此URL的帖子: http : //posttestserver.com/post.php?dir=anyNameYouWillFind
And can see your posts there: http://posttestserver.com/data/ 并可以在此处查看您的帖子: http : //posttestserver.com/data/
Browse to year, month, day and anyNameYouWillFind .. 浏览到年,月,日和anyNameYouWillFind ..
OLD: 旧:
you have to prefix your url!! 你必须给你的网址加上前缀!
this.http.get(' http ://localhost:8080/v1_user/45646/team'); this.http.get(' http :// localhost:8080 / v1_user / 45646 / team');
Fixed it by adding this to the backend node.js 通过将其添加到后端node.js来修复它
// access control --> allowed all origin
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
})
.options('*', function(req, res, next){
res.end();
})
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.