【问题标题】:Curl is getting POST response but node.js is not getting POST responseCurl 得到 POST 响应,但 node.js 没有得到 POST 响应
【发布时间】:2016-01-09 05:39:30
【问题描述】:

当我使用以下命令时,我得到正确的 JSON 响应:

$ curl --data "regno=<reg-number>&dob=<dob>&mobile=<mobile>"  https://vitacademics-rel.herokuapp.com/api/v2/vellore/login

当我使用以下 Node JS 代码时,我没有得到响应:

var request= require('request');
var querystring=require('querystring');

var credentials={regno: '13bit0036', dob:25051995, mobile:9431222422};
console.log(querystring.stringify(credentials));
request.post({
url: 'https://vitacademics-rel.herokuapp.com/api/v2/vellore/login',

headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body:querystring.stringify(credentials),
}, function(error, response, body){
if(error) {
    console.log(error);
} else {
    console.log(response.statusCode + '\n' , body);
}
});

【问题讨论】:

  • 您查看过实际发送的请求吗?我怀疑这不是您想要的,因为 jsonrequest 的布尔参数。
  • 是的,我看了看,发现 json 不是发送数据的正确数据类型。所以我修改了代码。当前代码写在上面。当内容类型设置为“application/x-www-form-urlencoded”时,HTTP 请求程序插件(在 forefox 中)会给出正确的响应。但是node.js的输出还是不正确,

标签: node.js post curl response


【解决方案1】:

将标头添加到您的请求中,如下所示:

headers: {
    'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0',
    'host': 'vitacademics-rel.herokuapp.com',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Connection':'keep-alive'
},

您将收到所需的回复:

lalit@ubuntu-0:~$ node requesting.js 
regno=13bit0036&dob=25051995&mobile=9431222422
200
{"reg_no":"13BIT0036","dob":"25051995","mobile":"9431222422","campus":"vellore","status":{"message":"Successful execution","code":0}}

当你做 curl 时,它会默认添加这些标题。

当您从客户端或库User-AgenthostConnection 进行连接时,应始终添加标头。通常所有网站都需要这些标头。

要获取这些标头的值,请在浏览器中运行 URL 并按 F12,在 Net 中读取浏览器发送的请求标头数据。在您的请求中输入相同的标题。

【讨论】:

    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2018-01-01
    • 2021-06-30
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多