2016-09-22 30 views
0

在後端的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); 

    } 

回答

1

已更新:

對於您的新錯誤消息:Angular2是較低層的標頭。 請更新您的後端以接受content-type

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

您不能測試後的這個網址:http://posttestserver.com/post.php?dir=anyNameYouWillFind

而且可以看到自己的帖子有:http://posttestserver.com/data/

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

OLD:

你必須爲你的網址加個前綴!!

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

+0

你的意思是我要補充的 「http://本地主機:8080/v1_user/45646 /團隊」 這個URL在客戶端吧?? – kohli

+1

請發佈您的Angular2 get方法。 – mxii

+0

我用它來發布我已編輯的問題 – kohli

0

加入這個到後端固定它的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(); 
}) 
;