【发布时间】:2020-09-11 04:54:27
【问题描述】:
尝试从 http 帖子中 console.log 节点脚本中的数据
const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));
const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static('public'));
app.post('/do-login', function(req, res) {
console.log( req.body );
});
在客户端,我使用 javascript fetch 将数据发送到节点后端
let data = {
email :'test@domain.com',
password : 'test'
}
fetch('http://localhost:3700/do-login',{
method : 'post',
body : JSON.stringify(data)
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
});
但不走运,它返回一个空对象
但是,如果我使用帖子xmlHttpRequest
var http = new XMLHttpRequest();
var url = 'http://localhost:3700/do-login';
var params = 'email=test@domain.com&password=test';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
我能够接收到客户端发送的数据。有什么问题?
非常感谢任何帮助和想法。
【问题讨论】:
-
您的 fetch 正在发送 JSON ...您的 XHR 正在发送
application/x-www-form-urlencoded... 这两段代码没有可比性 -
解决方案 1) 在使用 fetch 时发送 x-www-form-urlencoded 数据,或 2) 在 fetch 请求中将 content-type 设置为 application/json
-
@JaromandaX 我愿意接受你的回答,请发表。
-
别人的回答也一样好 - 我不会回答
标签: javascript node.js express fetch