首页 > CORS收发post异步请求在nodejs下失败问题

CORS收发post异步请求在nodejs下失败问题

想用cors收发异步请求,我是这样做的:

先造一下假数据尝试一下:

  var mydata = {
        id:timestamp,
        pass:"14444",
        title:"24444",
        tag:"34444",
        content:"544444"
    };
    var XHR = new XMLHttpRequest();
    XHR.open("POST", "http://localhost:8090/savemycollec");
    XHR.setRequestHeader('Content-Type', 'application/json');
    XHR.onreadystatechange = handler;
    XHR.send(JSON.stringify(mydata));

服务端:

        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept');
        res.header('Access-Control-Allow-Methods', 'POST,GET,DELETE,PUT');
        console.log(req.body);
        console.log(req.query);
        res.end();

检测值,

结果发现:

仍然是报错:

XMLHttpRequest cannot load http://localhost:8090/savemycollec. 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:63342' is therefore not allowed access.

貌似是不能直接接受json格式的请求?

如果把请求中setRequestHeader去掉的话就不报错了但是传空值(收不到数据)

请相关经验人士指点一二,


res.set('Access-Control-Allow-Headers', 'Content-Type');
res.set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT');

【热门文章】
【热门文章】