PUT 请求中未定义正文

问题描述 投票:0回答:1

我有一个 React / Redux / Node 应用程序正在请求更新用户:

client/src/components/pages/AlignmentPage.tsx

const AlignmentPage = () => {
  const dispatch = useAppDispatch();
  const [alignment, setAlignment] = useState("");
  const user: User | null = useAppSelector(
    (state: RootState) => state.userData.user
  );

  const handleSetAlignment = (value: string) => {
    setAlignment(value);
    displayNewAlignment(value);
    if (user) {
      console.log("in AlignmentPage.tsx:", { alignment: value });
      dispatch(updateUser(user._id, { alignment: value }));
    }
  };
...

在我的 Redux 操作中,我们正在为用户调用 PUT 端点:

export const updateUser = (userId: string, data: any) => async (dispatch: any) => {
  try {
    dispatch(setLoadingAction(true));

    const response = await fetch(`http://localhost:5000/api/user/${userId}`, {
      method: 'PUT',
      cache: 'no-cache',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    });

    const updatedData = await response.json();
    dispatch(updateUserAction(updatedData.user));
  } catch (error) {
    dispatch(setErrorAction('error updating user!'));
  }
}

控制器端点如下所示:

exports.updateUser = asyncHandler(async (req: any, res: any, next: any) => {
  const { userId } = req.params;
  console.log(req.body)
  const data = req.body;

  const user = await updateUser(userId, data);

  res.status(200).json({ user });
});

出于某种原因,在控制器中,我可以很好地注销 userId 参数。但主体总是返回

undefined
,因此 Redux 存储和 Mongo 中的文档不会被更新。我能够成功记录“数据”,直到在 Redux 操作中调用
const response = await fetch(http://localhost:5000/api/user/${userId}"
updatedData
记录器返回原始 MongoDB 对象,但没有更新的字段(“对齐”):

Object { user: {…} }
​user: Object { _id: "65d73ae14d1a69c64d6787e6", ipAddress: "::ffff:127.0.0.1", createdAt: "2024-02-22T12:15:29.745Z", … }
​​__v: 0
​​_id: "65d73ae14d1a69c64d6787e6"
​​alignment: ""
​​createdAt: "2024-02-22T12:15:29.745Z"
​ipAddress: "::ffff:127.0.0.1"

似乎有什么东西阻止了主体被发送到控制器。我不确定这是否是我设置路由器的方式或什么。我在其他地方读到这可能是由于服务器端没有安装

bodyParser
中间件,所以我在我的
server.ts
文件中实现了这个,但这似乎并没有解决问题。

(async () => {
  const port = env.PORT;
  app.use(express.json());
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use('/api/user', userRouter);

  try {
    app.listen(port, () => {
      db.on("error", console.error.bind(console, "connection error:"));
      db.on("connected", function () {
        console.log("Connected to MongoDB");
      });
      console.log(`Server started at http://localhost:${port}`);
    });
  } catch (err) {
    const error = new Error("Request failed");
    console.log(err);
    throw error;
  } finally {
    console.log("Server started");
  }
})();

api/src/routes/user.ts

router.get("/api/user", userController.getUser);
router.put("/api/user/:userId", userController.updateUser);

export { router };

添加了记录器和 redux 负载的屏幕截图:

reactjs express undefined put
1个回答
0
投票

我明白了。

在调用用户控制器端点时,我需要传递

express.json()
作为参数。

api/src/routes/user.ts

router.put("/api/user/:userId", express.json(), userController.updateUser);

api/src/controllers/user.ts

exports.updateUser = asyncHandler(async (req: any, res: any, next: any) => {
  const { userId } = req.params;
  const data = req.body;

  const user = await updateUser(userId, data);

  res.status(200).json({ user });
});

数据现已成功更新:)

© www.soinside.com 2019 - 2024. All rights reserved.