2015-06-29 42 views
0

我得到一個錯誤CORS而POST請求, 我的服務器的NodeJS的樣子:訪問控制允許來源的POST請求 - 節點

var express = require('express'); 
var app = express(); 
app.set('port', (process.env.PORT || 5000)); 
app.use(express.static(__dirname + '/public')); 

app.use(function(request, response, next) { 
    response.header('Access-Control-Allow-Origin', '*'); 
    response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); 
    response.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); 

    next(); 
}); 

app.post('/InsertClient', function(request, response){ 

    console.log(request.body);  // your JSON 
    response.send(request.body); // echo the result back 

}); 

我嘗試已經設置的標頭。 有什麼想法? 謝謝大家!

+0

您可能想要使用這個小模塊:https://www.npmjs.com/package/cors –

回答

1

你應該在同一URL添加OPTIONS路線爲POSThttps://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

喜歡的東西:

app.options('/InsertClient', function(request, response){ 
    response.sendStatus(200); 
}); 

瀏覽器會那麼首先調用URL與OPTIONS方法,並檢查是否有所有相應的Cors標誌,然後進行實際的POST請求。

相關問題