как исправить PUT, ошибка 500 id = undefined ReactJs NodeJs - PullRequest
0 голосов
/ 17 марта 2020

Я хотел бы объяснить мою проблему дня.

ошибка 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

1 Ответ

0 голосов
/ 17 марта 2020

Замените строку userId этим:

 const userId = req.body.userIdData.id;

на ES6 Object Destructring:

const { id } = req.body.userIdData

Кроме того, будет лучше, если вы удалите объявление formData, так как оно не используется в обработчике маршрута.

...