简体   繁体   English

CORS POST请求返回空体

[英]CORS POST Request Returns Empty Body

As the later stage from this question " Make POST JSON Request From HTML Script To A Node.JS App In Another Domain ", I implemented a CORS POST request: 作为此问题的后续阶段“ 将POST JSON请求从HTML脚本发送到另一个域中的Node.JS应用程序 ”,我实现了一个CORS POST请求:

var request = new XMLHttpRequest();
var params = "parameter=test";
request.open('POST', 'http://localhost:3009/param_upload', true);
request.onreadystatechange = function() {if (request.readyState==4) alert("It worked!");};
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);

It is pretty much close to the examples in the internet. 它非常接近互联网上的例子。 And this is my setup in my node.js server side: 这是我在node.js服务器端的设置:

app.use(cors());
var corsOptions = {
  origin: '*',
  credentials: true,
  allowedHeaders: ['*'],
  optionsSuccessStatus: 200
}

Of course, my app.post function has cors(corsOptions) in its header. 当然,我的app.post函数在其标题中有cors(corsOptions)。 However somehow the body is empty. 但不知何故,身体是空的。 As request I got a very long response which doesn't have the test text inside. 作为请求,我得到了一个很长的响应,里面没有测试文本。 I might be missing a point but looked around and coulnd't find it. 我可能会错过一个观点,但环顾四周,却找不到它。 If anyone helps, I will be very glad. 如果有人帮忙,我会很高兴。

I think you forgot to use BodyParser middleware. 我想你忘了使用BodyParser中间件。

https://github.com/expressjs/body-parser https://github.com/expressjs/body-parser

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

With this middleware all your body data will be in req.body. 使用此中间件,您的所有身体数据都将在req.body中。

Exemple: 例:

app.post('/test', function(req, res) {
    // body data
    console.log(req.body);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM