在Express中接收过帐数据(非表格)

时间:2019-03-23 02:10:43

标签: javascript node.js ajax post

我正在通过提示符获取字符串,我想将其从客户端发送到我的服务器(使用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的结果总是{}。如果有人能告诉我我在做什么错以及如何解决它,那将是很好的。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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