鍍金池/ 問答/HTML/ node 跨域訪問

node 跨域訪問

訪問node服務(wù)器跨域,post請求變成了options,設(shè)置請求頭后,獲取不到post請求提交的數(shù)據(jù)

var http = require('http');
var url = require("url");

http.createServer(function (req, res) {
    var urlObj = url.parse(req.url);
    var pathname = urlObj.pathname;
    // 關(guān)閉nodejs 默認訪問 favicon.ico
    if (!pathname.indexOf('/favicon.ico')) {
        return; 
    };
     let requestM=req.method;

    res.writeHeader(200,{
        "access-control-allow-origin": "*",
        "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
        "access-control-allow-headers": "Content-Type,Content-Length, Authorization, Accept,X-Requested-With",
        "access-control-max-age": 10,
        "Content-Type": "application/json"
    });

    if(requestM==="POST"){
        var post = '';  
                // 通過req的data事件監(jiān)聽函數(shù),每當(dāng)接受到請求體的數(shù)據(jù),就累加到post變量中
                req.on('data', function(chunk){    
                    post += chunk;
                });
    }
    //獲取不到post 請求過來的參數(shù)

}).listen(3000);
回答
編輯回答
冷眸

options請求是瀏覽器行為,因為跨域時瀏覽器(某些)會發(fā)送一個options請求來測試,如果這個請求被響應(yīng),才會進行后面的正常請求。

所以你只要針對options請求返回一個200的狀態(tài)碼即可。

2018年2月6日 20:18
編輯回答
尐懶貓

怎么post數(shù)據(jù)的,貼出來看下
另外我覺得在res寫頭沒有必要寫allow header 你的需求要求這么高嗎

2018年6月6日 12:58