首页 > 解决方案 > 如何修复 PUT,错误 500 id = undefined ReactJs NodeJs

问题描述

我想解释一下我今天遇到的问题。

错误 500,id = undefined,不知道为什么,我尝试发布您可能需要的任何内容

我该如何解决这个问题?

这就是功能

 handleSubmit = (e, id) => {
 e.preventDefault();
 const userIdData = { id };
 const config = {
 method: "PUT",
 headers: {
 "Content-Type": "application/json",
 },
  body: JSON.stringify({userIdData, livree: new Date().toISOString().slice(11, 16)}),
 };
   const url = entrypoint + "/alluserpls";
   fetch(url, config)
   .then(res => res.json())
     .then(res => {
     if (res.error) {
      alert(res.error);
       else {
        alert(`ajouté avec l'ID ${res}!`);
        }
        }).catch(e => {
        console.error(e);
        }).finally(() => this.setState({ redirect: true })); }

我的路线

 app.put('/api/alluserpls', (req, res, ) => {
 const formData = req.body;
 const userId = req.body.id;
 const deleteQuery = `UPDATE alluserpls SET ? WHERE id = ${userId}`;
 connection.query(deleteQuery, err => {
 if (err) {
 console.log(err)
 res.status(500).send("Erreur lors de la modification des users");
 } else {
 res.sendStatus(200);
 }
 });
 });

我的按钮

     <form onSubmit={(e) => this.handleSubmit(e, datass.id)}>
     <button type="submit">PUT</button>
     </form>

console.log 结果

  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to 
  your MariaDB server version for the right syntax to use near '? WHERE id = undefined' at 
  line 1",
  sqlState: '42000',
  index: 0,
  sql: 'UPDATE alluserpls SET ? WHERE id = undefined'
   }
  PUT /api/alluserpls 500 14.354 ms - 40

标签: mysqlnode.jsreactjsexpressfetch

解决方案


将 userId 行替换为:

 const userId = req.body.userIdData.id;

使用 ES6 对象解构:

const { id } = req.body.userIdData

此外,如果您删除声明,它会更干净,formData因为它没有在路由处理程序中使用。


推荐阅读