Node.js 正文未解析

Node.js body is not parsing

当我尝试通过快速服务器 post 一些数据到我的数据库时,正文没有得到解析。

我曾尝试使用 express.json(),但在无法正常工作后,我又回到了 bodyParser.json()。 None 这些东西奏效了,所以我上网了。我一直在看视频、阅读文章和通过堆栈溢出搜索 2 小时,但我找不到解决方案。

客户端(react.js):

fetch('http://localhost:7000/users', {
   method: 'POST',
   header: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
   },
   body: JSON.stringify({
      username: username,
      password: password
   })
});

服务器端(node.js 使用 express):

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。不确定这是否重要)

routes/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;

在客户端,我控制台记录了我发送到服务器的内容,结果是:

{"username":"testUser","password":"testPass"}

在服务器端,我控制台记录了我收到的内容,结果是:

{}

{ name: undefined, password: undefined }

如果我只是愚蠢而遗漏了一些简单的东西,或者是否有我应该添加或更改的东西,请告诉我。

提前感谢您的帮助!

我认为这只是一个错字。它应该是 'headers' 而不是 'header'.

fetch('http://localhost:7000/users', {
 method: 'POST',
 headers: {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
 },
 body: JSON.stringify({
  username: username,
  password: password
 })
});