当我尝试通过快速服务器将一些数据发布到我的数据库时,主体不会被解析。
我曾尝试使用 express.json() 并且在那之后不起作用,我又回到了 bodyParser.json()。这些事情都没有奏效,所以我上网了。我一直在看视频、阅读文章和搜索堆栈溢出两个小时,但我找不到解决方案。
客户端(react.js):
fetch('http://localhost:7000/users', {
method: 'POST',
header: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
username: username,
password: password
})
});
服务器端(带有 express 的 node.js):
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const http = require('http');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const index = require('./routes/index');
const users = require('./routes/users');
app.use('/', index);
app.use('/users', users);
const server = http.Server(app);
const port = 7000;
server.listen(port, () => {
console.log('Listening on port ' + port);
});
(我使用 http 服务器而不是 app.listen 的原因是因为我要添加 socket.io。不确定这是否重要)
路线/users.js:
const express = require('express');
const router = express.Router();
const mongo = require('mongojs');
const dbuser = SENSITIVE_INFO;
const dbpass = SENSITIVE_INFO;
const db = mongo('mongodb://'+dbuser+':'+dbpass+'@ds157574.mlab.com:57574/chat-app-1__saahilkhatkhate', ['users']);
router.get('/', (req, res, next) => {
db.users.find((err, users) => {
if (err) {
res.send(err);
}
res.json(users);
});
});
router.post('/', (req, res, next) => {
var body = req.body;
var data = {
name: body.username,
password: body.password
};
console.log(body);
console.log(data);
// db.users.save(data, (err, user) => {
// if (err) {
// res.send(err);
// }
// res.json(user);
// });
});
module.exports = router;
在客户端,我控制台记录了我发送到服务器的内容,结果是:
{“用户名”:“testUser”,“密码”:“testPass”}
在服务器端,我控制台记录了我收到的内容,结果是:
{}
{名称:未定义,密码:未定义}
请让我知道我是否只是愚蠢而遗漏了一些简单的东西,或者是否有一些我应该添加或更改的内容。
预先感谢您的帮助!
我认为这只是一个错字。它应该是“标题”而不是“标题”。
fetch('http://localhost:7000/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
username: username,
password: password
})
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句