簡體   English   中英

Google Chrome瀏覽器中API調用的跨域錯誤

[英]Cross orgin error in google chrome for the api call

在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();
});

但是在谷歌瀏覽器的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.

這是我正在使用的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);

    }

更新:

對於您的新錯誤消息:Angular2使用較低的標題框。 請也更新您的后端以接受content-type

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, content-type, Accept");

您無法測試此URL的帖子: http : //posttestserver.com/post.php?dir=anyNameYouWillFind

並可以在此處查看您的帖子: http : //posttestserver.com/data/

瀏覽到年,月,日和anyNameYouWillFind ..

舊:

你必須給你的網址加上前綴!

this.http.get(' http :// localhost:8080 / v1_user / 45646 / team');

通過將其添加到后端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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM