我尝试使用 Node JS 进行简单的用户注册,将 username
、email
和 password
发送到 '/newuser'
端点,可以在 user.js
中看到。
header 已正确发送,我可以在控制台中看到它,但我无法访问我感兴趣的 req.body
部分。我正在使用 body -parser
express 文档中建议的 express 中间件。
如果我打印出 req.body
,只有 [object Object]
被打印,如果我打印出 whole req
object 我在任何地方都看不到参数,如果我尝试 JSON.parse(req.body)
,那么当然 SyntaxError: Unexpected token o in JSON at position 1
出现。谁能指出我正确的方向?
前端的 JavaScript
我是这样做的,它应该是这样工作的(我也用ajax试过,但还是不行,同样的错误)。但是我发送的数据肯定是正确的,如果我在发送前打印出来,它就是一个有效的 JSON。
var xhr = new XMLHttpRequest();
xhr.open('POST', '/newuser');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.send(JSON.stringify({
username: data.username,
password: data.password,
email: data.email
}));
服务器.js
'use strict';
var express = require('express');
var hogan = require('hogan-express');
var http_module = require('http');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json('application/json'));
app.use(cors({credentials: true, origin: true}));
app.engine('html', hogan);
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
app.set('port', process.env.PORT || 4000);
app.use(express.static(__dirname + '/public'));
app.set('trust proxy', 1); // trust first proxy
const partials = {
header: 'partials/header',
footer: 'partials/footer'
};
require('./routes')(app, partials);
const http = http_module.Server(app);
http.listen(app.get('port'), () => {
console.info('Running on http://localhost:%s', app.get('port'));
});
module.exports = app;
路由.js
// Routes
module.exports = (app, partials) => {
require('./home')(app, partials);
require('./signup')(app, partials);
require('./user')(app, partials);
require('./404')(app, partials);
};
用户.js
module.exports = (app, partials) => {
app.post('/newuser', (req, res, next) => {
console.log(req.header('Content-Type'))
console.log(req.body) // this prints [object Object]
console.log(JSON.parse(req.body)) // this throws SyntaxError: Unexpected token o in JSON at position 1
});
};
最佳答案
因为您使用了 body-parser 的 json
解析器,所以当您获取 JSON 时,它已已经解析(这就是为什么您会看到 [object Object]
如果你 console.log
它 - 这就是你将对象强制转换为字符串时得到的结果,并且它没有为其定义任何特殊的 toString
*).
要访问您发送的对象的属性,请在 req.body
上访问它们:
app.post('/newuser', (req, res, next) => {
console.log(req.header('Content-Type'))
console.log(req.body.username); // <====
console.log(req.body.password); // <====
console.log(req.body.email); // <====
});
使用该代码,当我在本地运行您的代码时,我会看到 POSTed 数据。
* 除了 JJJ 在下面指出的,如果您真的使用 console.log
,您应该看到对象的表示,而不是 [object Object]
,几乎在任何版本的 Node 中。也许您正在使用其他强制字符串的东西?或者使用你没有展示的中间件,它可能会用 String(req.body)
覆盖 req.body
?
关于javascript - 使用 NodeJS 接收 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48042698/