简体   繁体   中英

Receiving Post data (not form) in Express

I am getting a string through a prompt and I want to send it from the client to my server (Which uses Express).

Client:

username = prompt('Enter your Username');
req.open('POST', url + 'username');
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencode;charset=UTF-8');
req.send(username);

Server:

app.use(bodyParser.urlencoded({
  extended: false
}));
app.post('/username', function(req, res) {
  console.log(req.body);
  res.end('ok bud');
});

And the result of req.body is always {} when the username var is something like 'test' or something. If anyone can tell me what I am doing wrong and how to fix it that would be great.

You've set your content type to 'application/x-www-form-urlencode;charset=UTF-8' Which requires the payload to be in key value pairs.

Since you want to post plain text, set your content type to 'text/plain' instead.

您没有在客户端通过提示获取的帖子请求中附加用户名。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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