2015-08-26 147 views
0

有問題將數據從http post請求回送到我正在構建的API。拋出錯誤:CORS錯誤:Angular.JS,Node.JS和Express

XMLHttpRequest cannot load (URL to API here). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:9000 ' is therefore not allowed access.

下面是在客戶端的角度代碼:

$http.post('MyAPI'sURLHere', {date: $scope.information.PubDate}) 
        .then(function(response){ 
         console.log(response); 
        }, function(error){ 
         console.log(error); 
        }); 

下面是我的API節點服務器端代碼:

app.post('/getThing', function(req, res){ 
     var date = req.body.date; 
     console.log(typeof date); 
     var query = Overquery 
     var query2 = "alter session set nls_date_format = 'MM/dd/yyyy'"; 
     console.log(query); 
     oracleDB.execute(query2, function(err, result){ 
       if(err){ 
         console.log(err.message); 
       } 
       else{ 
         console.log(result); 
       } 
     }); 
     oracleDB.execute(query, function(err, result){ 
       if(err){ 
         console.log(err.message); 
       } 
       else{ 
         res.header('Access-Control-Allow-Origin', '*'); 
         res.header('Access-Control-Allow-Methods', 'POST'); 
         res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); 
         console.log(result.rows); 
         res.json(result.rows); 
       } 
     }); 
}); 

第一次建立一個API所以任何建議和幫助將不勝感激!

+0

你正確設置CORS標頭的POST請求,然而,你可能在某些情況下,沒有正確迴應發出請求之前的OPTIONS請求。 –

回答

0

運行從一個bash shell中的項目如下:

npm install cors --save

它將安裝這樣的: https://github.com/expressjs/cors

然後創建應用程序時,將其添加到您的服務器。

var express = require('express'); 
var cors = require('cors'); 
var app = express(); 
app.use(cors()); 

編輯:這將使每一個域至極CORS是不推薦出於安全原因。請在這裏進行進一步CORS配置:https://github.com/expressjs/cors#configuring-cors

0

在您的節點應用,代碼此示例應解決您的問題:

// Allowing X-domain request 
var allowCrossDomain = function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Cache-Control"); 

    // intercept OPTIONS method 
    if ('OPTIONS' == req.method) { 
     res.send(200); 
    } 
    else { 
     next(); 
    } 
}; 
app.use(allowCrossDomain);