没有 post 带有 MongoDB 本机 NodeJS 驱动程序的请求正文

No post request body with MongoDB Native NodeJS driver

ExpressJS / MongoDB 本机 NodeJS 驱动程序

我很困惑为什么这个 post 请求一直没有请求正文返回。 Mongo 方法 insertOne 在技术上是 运行,但那里没有数据,所以它只输入空值。 get 请求工作正常。

app.js

import express from 'express';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
import mongoSanitize from 'express-mongo-sanitize';
import xss from 'xss-clean';
import hpp from 'hpp';

const app = express();

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100,
});

app.use(cors());
app.use(helmet());
app.use('/api', limiter);
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(mongoSanitize());
app.use(xss());
app.use(hpp());

app.get('/', (req, res) => {
  res.send('Hello World!!1 ');
});

export default app;

server.js

import mongodb from 'mongodb';

import app from './app.js';
import routes from './routes.js';

const port = process.env.PORT || 5000;
const uri = 'mongodb://127.0.0.1:27017/simon';
const client = new mongodb.MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

app.listen(port, () =>
  console.log(`✅ Server running on port ${port}... connecting to MongoDB...`)
);

(async function () {
  try {
    await client.connect();
    const db = client.db('simon');
    await db.command({ ping: 1 });
    console.log('✅ MongoDB connected');
    routes.forEach((route) => {
      route(app, db);
    });
  } catch (error) {
    console.error('❌ MongoDB connection error:', error.message);
  }
})();

routes.js

function getScores(app, db) {
  app.get('/api', async (req, res) => {
    try {
      const response = await db.collection('highScores').find().limit(5).toArray();
      console.log('response:', response);
      res.status(200).json(response);
    } catch (error) {
      console.error('Error getting scores:', error.message);
    }
  });
}

function addScore(app, db) {
  app.post('/api', async (req, res) => {
    const { name, score } = req.body;

    console.log('req.body:', req.body); // this always returns: {}

    try {
      const result = await db.collection('highScores').insertOne({ name, score });
      res.status(200).json(result);
    } catch (error) {
      console.error('Error adding score:', error.message);
    }
  });
}

export default [getScores, addScore];

post 请求的示例结果

{
    "result": {
        "n": 1,
        "ok": 1
    },
    "connection": {
        "_events": {},
        "_eventsCount": 4,
        "id": 1,
        "address": "127.0.0.1:27017",
        "bson": {},
        "socketTimeout": 0,
        "host": "127.0.0.1",
        "port": 27017,
        "monitorCommands": false,
        "closed": false,
        "destroyed": false,
        "lastIsMasterMS": 1
    },
    "ops": [
        {
            "_id": "610f70754792504433bba4e4"   // <- only the auto generated id
        }
    ],
    "insertedCount": 1,
    "insertedId": "610f70754792504433bba4e4",
    "n": 1,
    "ok": 1
}

我在 postman 中输入了什么

新创建的对象在mongodb

{
  _id: ObjectId('610f70754792504433bba4e4')
  name: null
  score: null
}

您的请求必须包含 header Content-Type: application/json。并且 JSON body 中的属性名必须用引号引起来:

{"name": "Jef", "score": 42}