在Express中接收Post数据(不是表单)

问题描述 投票:1回答:2

我通过提示获取字符串,我想将它从客户端发送到我的服务器(使用Express)。

客户:

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);

服务器:

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

当用户名var类似于'test'之类的东西时,req.body的结果总是{}。如果有人能告诉我我做错了什么以及如何解决这个问题会很棒。

javascript node.js ajax post
2个回答
1
投票

您已将内容类型设置为'application / x-www-form-urlencode; charset = UTF-8',这要求有效内容位于键值对中。

由于您要发布纯文本,请将内容类型设置为“text / plain”。


0
投票

您没有在客户端的帖子请求中附加用户名,这是通过提示进行的。

© www.soinside.com 2019 - 2024. All rights reserved.