NodeJS 请求正文为空对象

6l7fqoea  于 2022-12-12  发布在  Node.js
关注(0)|答案(1)|浏览(173)

我的堆栈是RTK查询、Node.js和express。
我添加了app.use(express.json())作为一个中间件,但我仍然只是得到一个空的身体。我的代码如下。
这是我的apiSlice(RTK查询):

export const apiSlice = createApi({
  reducerPath: "api",
  baseQuery: fetchBaseQuery({
    baseUrl: "http://localhost:3001",
    // credentials: "include",
  }),
  endpoints: (builder) => ({
    createRoom: builder.mutation({
      query: (tvId: string) => {
        console.log("Id from action", tvId);
        return {
          url: "/rooms",
          method: "POST",
          body: tvId,
        };
      },
    }),
  }),
});

当我调用createroom时,我得到了一个带有ID字符串的控制台日志。

this is the id from the action UEP8QtRAcNYr90xCAAAF

然后在路线上,这是我的代码:

router.post("/rooms", async(req, res) => {
        console.log("the tv id is ", tvId);
});

module.exports = router;

我得到的控制台日志是the tv id is {}
我的应用程序索引文件如下:

const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const cors = require("cors");

require("./db/mongoose");
const roomRouter = require("./routers/room");
const Room = require("./models/room");

const app = express();

app.use(cors());
app.use(express.json());

const server = http.createServer(app);


const io = new Server(server, {
    cors: {
        origin: "http://localhost:3000",
        methods: ["GET", "POST"],
    },
});

io.on("connection", (socket) => {
    socket.on("get-room", async(roomId, user) => {
        try {
            const room = await Room.findById(roomId);

            if (!room.users.some((u) => u.id === user.id)) {
                room.users = [...room.users, user];
            }
            await room.save();
            socket.broadcast.to(roomId).emit("user-joined", user);
            socket.join(roomId);
            socket.emit("load-room", room);
        } catch (e) {
            console.log("failed something", e);
        }
    });
});

app.use(roomRouter);

server.listen(3001, () => {
    console.log("SERVER IS RUNNING");
});

那么为什么请求体总是出现呢?

drnojrws

drnojrws1#

我一发帖就解决了这个问题。我把答案贴出来,而不是删除它,以防将来有人遇到同样的问题。
看来从我面前送来的身体必须是一个物体,所以简单地改变一下:

return {
      url: "/rooms",
      method: "POST",
      body: tvId,
    };

对此:

return {
      url: "/rooms",
      method: "POST",
      body: {tvId: tvId}, // Could also just be written as {tvId}
    };

解决了。

相关问题