1

当我尝试使用node-postgres客户端运行此代码时,我得到“错误:没有参数 $1” :

app.post('/newcause', function (req,res){
  console.log(req.body);

  var g;

  var r = [];

  for (g in req.body)
  {
    r[g]=req.body[g];
    console.log('r[g] is ' + r[g]);
  }

  client = pg.connect(connectionString, function(err, client, done){
    if(err) console.log(err);
    client.query('INSERT INTO causes (cause_name, goal, organization, sponsor, submitter) VALUES ($1,$2,$3,$4,$5)', r, function(err){
      console.log('This is r' + r)
      if (err) console.log(err);
    });    
  });
});

有什么建议吗?

PS,这是完整的错误声明:

{ [error: there is no parameter $1]
  name: 'error',
  length: 87,
  severity: 'ERROR',
  code: '42P02',
  detail: undefined,
  hint: undefined,
  position: '81',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  file: 'parse_expr.c',
  line: '812',
  routine: 'transformParamRef' }
4

1 回答 1

1

执行查询的错误意味着r没有正确填充。明确用户输入是值得的,这样您的系统就不会在下游(在查询中)而不是在问题根源处引发错误:

app.post('/newcause', function (req,res){
  console.log(req.body);

  var g;

  var r = [];

  r.push(req.body.causename, req.body.Goal, req.body.Organization, req.body.sponsor, req.body.submitterEmail);

  client = pg.connect(connectionString, function(err, client, done){
    if(err) console.log(err);
    client.query('INSERT INTO causes (cause_name, goal, organization, sponsor, submitter) VALUES ($1,$2,$3,$4,$5)', r, function(err){
      console.log('This is r' + r.toString())
      if (err) console.log(err);
    });    
  });
});

还值得一提的是,在帖子提交中标准化您的变量名称大小写可能是一个好主意。

于 2013-10-18T18:27:41.743 回答