我通过提示获取字符串,我想将它从客户端发送到我的服务器(使用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的结果总是{}。如果有人能告诉我我做错了什么以及如何解决这个问题会很棒。
您已将内容类型设置为'application / x-www-form-urlencode; charset = UTF-8',这要求有效内容位于键值对中。
由于您要发布纯文本,请将内容类型设置为“text / plain”。
您没有在客户端的帖子请求中附加用户名,这是通过提示进行的。