Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用PostgreSQL请求在数组中循环_Javascript_Node.js_Postgresql - Fatal编程技术网

Javascript 使用PostgreSQL请求在数组中循环

Javascript 使用PostgreSQL请求在数组中循环,javascript,node.js,postgresql,Javascript,Node.js,Postgresql,我试图在数据库中存储数组的内容。我想为数组中的每个项添加新行。目前我正在运行: router.post('/saveVenueMatches', (req, res) => { const id = req.body.user_id; const data = req.body.data; res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); for (const venue of da

我试图在数据库中存储数组的内容。我想为数组中的每个项添加新行。目前我正在运行:

router.post('/saveVenueMatches', (req, res) => {
  const id = req.body.user_id;
  const data = req.body.data;
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
  for (const venue of data) {
    let sqlText = `INSERT INTO user_matches (user_id, venue_id) VALUES ($1, $2)`;
    pool
      .query(sqlText, [id, venue.id])
      .then((response) => {
        res.send(response.rows);
      })
      .catch((err) => {
        console.log('Error saving venue matches', err);
      });
  }
});
这将导致成功发布到我的数据库,但是我的服务器会为数组中的每个项目返回一次以下错误:

Error saving venue matches Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
{
  code: 'ERR_HTTP_HEADERS_SENT'
}
我尝试删除设置标题的行,但仍然出现错误。我不太清楚是什么原因造成的


此外,如果有更好的方法提出这样的请求,请让我知道。

您试图在一个周期的每个迭代中将结果发送给客户,但您只能执行一次。尝试在一个周期后发送结果,或者最好将该周期转换为
承诺。所有
调用

我的建议是一次使用多个插入,不要尝试多次访问数据库

您可以一次使用此npm包进行多个插入

const pg = require('pg');
const format = require('pg-format');
您只需要相应地格式化数据

let user_matches = [[1, 2], [2, 3]];
let query1 = format('INSERT INTO users (user_id, venue_id) VALUES %L returning id', user_matches);
let {rows} = await client.query(query);
请访问本网站以供参考 点击