“Cannot PUT /mytable”when running `UPDATE` SQL command from react-postgres“React App”localhost:MYPORT on PostgreSQL/node.js backend

lf3rwulv  于 2023-04-20  发布在  Node.js
关注(0)|答案(3)|浏览(118)

我在https://github.com/nsebhastian/react-node-postgres上遵循指南。根据博客下面的评论,我可以确认完整的教程是有效的,请参阅TypeError: Cannot read property 'rows' of undefined上的文档。
ADDDELETE命令工作,SELECT显示表merchant
博客结尾:
我将UPDATE查询的实现留给您作为练习。
我就想,为什么不试试?这都是几个小时前的事了...
我只是取了GitHub仓库中提供的确切文件。
在“/node-postgres”目录中,我更改了:

  • “index.js”,在底部添加:
app.put('/merchants', (req, res) => {
  merchant_model
    .updateMerchant(req.body)
    .then((response) => {
      res.status(200).send(response);
    })
    .catch((error) => {
      res.status(500).send(error);
    });
});
  • “merchant_model.js”通过在底部添加和更改,几乎复制了createMerchant的功能指南。

原始createMerchant函数:

const createMerchant = (body) => {
  return new Promise(function (resolve, reject) {
    const { name, email } = body;

    pool.query(
      'INSERT INTO merchants (name, email) VALUES ($1, $2) RETURNING *',
      [name, email],
      (error, results) => {
        if (error) {
          reject(error);
        }
        resolve(
          `A new merchant has been added added: ${JSON.stringify(
            results.rows[0]
          )}`
        );
      }
    );
  });
};

新的updateMerchant函数:

const updateMerchant = (body) => {
  return new Promise(function (resolve, reject) {
    const { id, name } = body;
    pool.autoCommit = true;

    pool.query(
      'UPDATE merchants SET name = "$2" WHERE id = $1',
      [id, name],
      (error, results) => {
        if (error) {
          reject(error);
        }
        resolve(
          `A merchant has been updated: ${JSON.stringify(results.rows[0])}`
        );
      }
    );
  });
};

module.exports = {
  getMerchants,
  createMerchant,
  deleteMerchant,
  updateMerchant,
};

在/node-postgres/react-postgres目录中,我更改了(因为Need help about @Get @Post @Put @Delete in Restful webserviceExplain and example about 'get', 'delete', 'post', 'put', 'options', 'patch', 'head' method?,所以使用PUT方法为UPDATE):

  • “App.js”,在底部添加和更改:
function updateMerchant() {
  let id = prompt('Enter merchant ID');
  let name = prompt('Enter merchant name');

  fetch('http://localhost:3001/merchants', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ id, name }),
  })
    .then((response) => {
      return response.text();
    })
    .then((data) => {
      alert(data);
      getMerchant();
    });
}

return (
  <div>
    {merchants ? merchants : 'There is no merchant data available'}
    <br />
    <button onClick={createMerchant}>Add</button>
    <br />
    <button onClick={deleteMerchant}>Delete</button>
    <br />
    <button onClick={updateMerchant}>Update</button>
  </div>
);

当我在浏览器的React应用程序中点击localhost:3000时,我得到了idname的正确问题,运行... 'UPDATE merchants SET name = "$2" WHERE id = $1', [id, name] ...

以及:

然后抛出错误:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>Cannot PUT /merchants</pre> </body> </html>

这是什么,但这个错误消息在html(我只需要格式为markdown报价在这里得到这个):
错误

Cannot PUT /merchants

当我在没有参数化的情况下运行UPDATE时,错误保持不变:

... 'UPDATE merchants SET name = "test" WHERE id = 2', [id, name] ...

我试过从PUT方法切换到POST,但是每个UPDATE只是为email添加一个新的商家,并为email添加一个新的id和null值,请参阅上面的屏幕截图。SQL中的记录不会通过UPDATE命令更新,您可以实时看到表中第一行的变化。
我应该怎么做才能让UPDATE工作?

更新:

如answer + comment所示,使用“”会生成一个字段。但这并不能解决问题,我将代码改为'UPDATE merchants SET name = $2 WHERE id = $1',因为参数不需要引号,并且我在“node.js”终端中得到错误,停止了“node.js”服务:

my_user@MY_PC:~/my_project/node-postgres$ node index.js
App running on port 3001.
/home/my_user/my_project/node-postgres/merchant_model.js:61
      resolve(`A merchant has been updated: ${JSON.stringify(results.rows[0])}`)
                                                                     ^

TypeError: Cannot read property 'rows' of undefined
    at pool.query (/home/my_user/my_project/node-postgres/merchant_model.js:61:70)
    at Query.client.query [as callback] (/home/my_user/my_project/node-postgres/node_modules/pg-pool/index.js:387:18)
    at Query.handleError (/home/my_user/my_project/node-postgres/node_modules/pg/lib/query.js:128:19)
    at Client._handleErrorMessage (/home/my_user/my_project/node-postgres/node_modules/pg/lib/client.js:335:17)
    at Connection.emit (events.js:198:13)
    at parse (/home/my_user/my_project/node-postgres/node_modules/pg/lib/connection.js:114:12)
    at Parser.parse (/home/my_user/my_project/node-postgres/node_modules/pg-protocol/dist/parser.js:40:17)
    at Socket.stream.on (/home/my_user/my_project/node-postgres/node_modules/pg-protocol/dist/index.js:11:42)
    at Socket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
更新2:

正如我在评论中所要求的,我打开了这个测试数据库的日志。下面是它工作之前的最后一个查询:

2021-09-20 23:33:09.071 CEST [2637] my_user@my_database LOG:  statement: SELECT * FROM merchants ORDER BY id ASC
2021-09-20 23:33:44.346 CEST [2641] my_user@my_database ERROR:  bind message supplies 2 parameters, but prepared statement "" requires 0
2021-09-20 23:33:44.346 CEST [2641] my_user@my_database STATEMENT:  UPDATE merchants SET name = 'test' WHERE id = 2
2021-09-20 23:37:37.465 CEST [2674] my_user@my_database LOG:  statement: SELECT * FROM merchants ORDER BY id ASC
2021-09-20 23:37:38.586 CEST [2674] my_user@my_database LOG:  statement: SELECT * FROM merchants ORDER BY id ASC
2021-09-20 23:37:46.853 CEST [2674] my_user@my_database ERROR:  bind message supplies 2 parameters, but prepared statement "" requires 1
2021-09-20 23:37:46.853 CEST [2674] my_user@my_database STATEMENT:  UPDATE merchants SET name = '$2' WHERE id = $1
2021-09-20 23:41:16.399 CEST [2704] my_user@my_database LOG:  statement: SELECT * FROM merchants ORDER BY id ASC
2021-09-20 23:41:31.879 CEST [2706] my_user@my_database ERROR:  bind message supplies 2 parameters, but prepared statement "" requires 1
3bygqnnd

3bygqnnd1#

这里是你需要得到正确更新商家表的一切。

app.put('/merchants/:id', (req, res) => {
  merchant_model.updateMerchant(req.body)
    .then(response => {
      res.status(200).send(response);
    })
    .catch(error => {
      res.status(500).send(error);
    })
})



const updateMerchant = (body) => {
  return new Promise(function(resolve, reject) {
    const {
      id,
      name,
      email
    } = body
    pool.query('UPDATE merchants SET name = $2, email = $3 WHERE id = $1', [id, name, email], (error, results) => {
      if (error) {
        reject(error)
      }
      resolve(`Merchant ${id} updated`)
    })
  })
}


function updateMerchant() {
  let id = prompt("Enter Merchant Id");
  let name = prompt("Enter merchant name");
  let email = prompt("Enter merchant email");
  fetch(`http://localhost:3001/merchants/${id}`, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        id,
        name,
        email
      }),
    })
    .then((response) => {
      return response.text();
    })
    .then((data) => {
      alert(data);
      getMerchant();
    });
}
62o28rlo

62o28rlo2#

该问题可能与语句'UPDATE merchants SET name = "$2" WHERE id = $1'有关
在Postgres中,双引号表示字段名,而不是值。您需要使用单引号。

rslzwgfq

rslzwgfq3#

有许多错误的步骤导致了这个问题。
1.我复制了createMerchant函数的代码,忘记更改

resolve(`A merchant has been updated: ${JSON.stringify(results.rows[0])}`)

results.rows是空的,如果我只是更新一些东西,它们只有在创建新行时才有值。现在它可以使用:

const updateMerchant = (body) => {
  return new Promise(function(resolve, reject) {
    const { id, name } = body
    
    pool.query("UPDATE merchants SET name = $2 WHERE id = $1 RETURNING *", [id, name], (error, results) => {        
      if (error) {
        reject(error)
      }
      resolve(`Merchant updated with ID: ${id}, changed name to ${name}.`)
    })
  })
}

1.但是当我现在使用错误的results.rows的旧版本时,我也得到了同样的错误,即使引号是正确的:

/home/my_user/my_project/node-postgres/merchant_model.js:61
      resolve(`A merchant has been updated: ${JSON.stringify(results.rows[0])}`)
                                                                     ^

TypeError: Cannot read property 'rows' of undefined
    at pool.query (/home/my_user/my_project/node-postgres/merchant_model.js:61:70)
    at Query.client.query [as callback] (/home/my_user/my_project/node-postgres/node_modules/pg-pool/index.js:387:18)
    at Query.handleError (/home/my_user/my_project/node-postgres/node_modules/pg/lib/query.js:128:19)
    at Client._handleErrorMessage (/home/my_user/my_project/node-postgres/node_modules/pg/lib/client.js:335:17)
    at Connection.emit (events.js:198:13)
    at parse (/home/my_user/my_project/node-postgres/node_modules/pg/lib/connection.js:114:12)
    at Parser.parse (/home/my_user/my_project/node-postgres/node_modules/pg-protocol/dist/parser.js:40:17)
    at Socket.stream.on (/home/my_user/my_project/node-postgres/node_modules/pg-protocol/dist/index.js:11:42)
    at Socket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)

问题是我经常不重启node.js,而只是reactJS。我习惯在node.js后端时获得所有js文件的实时更新,但在前端,这当然是不同的!你需要重启node.js才能应用前端的更改。当重启node.js时,作为前端的“React App”可以进一步运行,并且一旦再次运行就会找到后端。
1.只有当我重新启动node.js时,我才得到新设置的真实的错误,包括错误的“”引号。
1.因此,最初的错误Cannot PUT /merchant可能是来自今天项目的一个稍微旧的版本,在那里我尝试向fetch地址添加参数,如fetch(\ http://localhost:3001/merchants/${id},{和其他测试。我缺乏勇气和时间来重现这个错误。也许,在它最终工作之前,它可能仍然被问题底部的日志输出所覆盖,它说:

2021-09-20 23:33:44.346 CEST [2641] my_user@my_database ERROR:  bind message supplies 2 parameters, but prepared statement "" requires 0

至少,现在解决了第一个工作UPDATE查询的日志输出:

2021-09-20 23:47:51.648 CEST [2792] my_user@my_database LOG:  execute <unnamed>: UPDATE merchants SET name = $2 WHERE id = $1 RETURNING * 2021-09-20 23:47:51.648 CEST [2792] my_user@my_database DETAIL:  parameters: $1 = '2', $2 = 'asdf' 2021-09-20 23:48:03.374 CEST [2795] my_user@my_database LOG:  statement: SELECT * FROM merchants ORDER BY id ASC

更新ID 2的示例屏幕截图:

按F5键:

相关问题