【问题标题】:Receiving Post data (not form) in Express在 Express 中接收 Post 数据(不是表单)
【发布时间】:2019-03-23 02:10:42
【问题描述】:

我通过提示获取一个字符串,我想将它从客户端发送到我的服务器(使用 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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 对不起,我错过了最后一行
      • 我在阅读您的问题时错过了 req.send(username) 这一行。
      猜你喜欢
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 2016-03-01
      相关资源
      最近更新 更多