2017-03-06 136 views
2

我試圖使用$ HTTP方法從一個角1個項目擊中端口3000的本地服務器上的一個節點API,但我收到此錯誤:

XMLHttpRequest cannot load http://localhost:3000/login . Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

我在節點JS還添加了Access-Control-Allow-Origin : *爲:

req.on('end', function() { 
    req.rawBody = req.rawBody.toString('utf8'); 
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost'); 
    // Request methods you wish to allow 
    res.setHeader('Access-Control-Allow-Methods', '*'); 
    // Request headers you wish to allow 
    res.setHeader('Access-Control-Allow-Headers', '*'); 
    // Set to true if you need the website to include cookies in the requests sent 
    // to the API (e.g. in case you use sessions) 
    // res.setHeader('Access-Control-Allow-Credentials', false); 
    next(); 
}); 

我的角度代碼:

var req = { 
      method: 'POST', 
      url: 'http://localhost:3000/login', 
      headers: { 
       'Content-Type': 'application/json', 
       // 'cache-control': 'no-cache' 
      }, 
      data: { username: username, password: password }, 
      json: true 
     }; 

     $http(req).then(function successCallback(response){ 
      console.log(response); 
     }, function errorCallback(response){ 
      console.log("Error : "); 
      console.log(response); 
     }); 

但是還是我得到這個錯誤。

回答

2

錯誤出現在指定的預檢響應中。 所以,你需要處理OPTIONS方法:

req.on('end', function() { 
    req.rawBody = req.rawBody.toString('utf8'); 
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost'); 

    // Request methods you wish to allow 
    res.setHeader('Access-Control-Allow-Methods', '*'); 

    // Request headers you wish to allow 
    res.setHeader('Access-Control-Allow-Headers', '*'); 

    // Set to true if you need the website to include cookies in the requests sent 
    // to the API (e.g. in case you use sessions) 
    // res.setHeader('Access-Control-Allow-Credentials', false); 


    if (req.method === "OPTIONS") { 
     return res.status(200).end(); 
    } 

    return next(); 
}); 

這是由於瀏覽器處理跨域請求的方式。 OPTIONS請求(預檢)在POST之前發送,以獲取允許的來源,標題和方法。