2017-05-26 55 views
0

我试图通过节点js发送HTTP POST请求。发送变量以在请求中形成参数HTTP POST节点js

这里是我的代码:

var tentativa = "{ id:'" + result.rows[i][0] + "', timestamp:'" + result.rows[i][1]+"', application: '"+ applicationName + 
       "', type:'Log', source: '" + result.rows[i][2] + "', " + string+ " }"; 

      request({ 
       uri: "http://localhost:5000/logs", 
       method: "POST", 
       form: tentativa, 
       headers: { 'Content-Type' : 'application/x-www-form-urlencoded' } 
       }, function(error, response, body) { 
       console.log(body); 

      }); 

当我送“tentativa”变量的形式,请求其派出,但没有任何保存。但是当我发送“tentativa”变量的输出时,它工作正常。它不应该一样吗?

+0

'form'属性应该可能只是一个普通的JavaScript对象,而不是对象的字符串表示。 'request'库会将它转换为你并正确地将其编码到HTTP请求中。 – varbrad

+0

“...请求抛出Node.js”你的意思是node.js抛出一个错误?什么是错误? – borislemke

+0

@borislemke它不是扔是通过。对错误感到抱歉 –

回答

0

这不是一个有效的JSON

var tentativa = "{ id:'" + result.rows[i][0] + "', timestamp:'" + result.rows[i][1]+"', application: '"+ applicationName + 
       "', type:'Log', source: '" + result.rows[i][2] + "', " + string+ " }"; 

的最后一个值错过关键属性,这可能是为什么它不与请求一起发送的对象。

既然看起来你想发送一个普通的json,你可以把对象放在body中。

request({ 
    uri: "http://localhost:5000/logs", 
    method: "POST", 
    body: tentativa, 
    json: true, 
    headers: { "Content-Type": "application/json"} 
    } 

    }, function(error, response, body) { 
     console.log(body); 

    }); 
0

非常感谢您的帮助。 使用javascript对象而不是该字符串解决了问题,就像@varbrad所说的那样。