错误:没有参数$ 1

时间:2013-10-14 23:36:56

标签: javascript node.js postgresql node-postgres

当我尝试使用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' }

1 个答案:

答案 0 :(得分: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);
    });    
  });
});

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