【问题标题】:Post request doesn't work in NodeJS, OK with Request发布请求在 NodeJS 中不起作用,可以使用 Request
【发布时间】:2019-12-23 04:15:22
【问题描述】:

我正在尝试使用 Axios,因为它是 NodeJS 中唯一具有异步/等待功能的模块。

我已经有一个 Python 脚本中的 POST 请求,效果很好,我正在尝试在 NodeJS 服务器上进行调整。

但我阻止了我的第一个帖子请求。 如果我直接使用 Request 模块,效果很好,请参阅我的代码:

console.log("create session");
let data = {'uname': 'login', 'pass':  'password', 'module':'NSUser', 'op':'login','url':'%2Findex.php'}
let url = 'https://localhost:9000/user.php'
let headers = {'Accept': "application/html"}

//s = request.session
body = await request.post({url:url, headers:headers, form:data}, function(error, response, body){
  console.log("LOGIN");
 console.log(response);

});

使用 Axios(或 Axios 实例,但它是供以后使用的......)因为我需要保持我的会话(就像在 Python 中一样,它就像一个魅力一样工作)。

     const config = {
      method: 'post',
      url: 'https://localhost:9000/user.php',
      headers:  {'content-type': 'application/x-www-form-urlencoded'},
      data: {uname:'login',
        pass:'password',
        module:'NSUser',
        op:'login',
        url:'/index.php'}
     }    
    axios(config)

作为响应的正文,它不是连接页面而不是带有请求的代码。

我错了什么? 我尝试用参数替换数据,但它是一样的......

如果需要,我有来自 Firefox 的 CURL 命令。

有关信息,在 python 中:

s = requests.session()
res = s.post(url, headers=headers, data=data)

和我的 s 变量有会话,并且可以请求所有连接。

【问题讨论】:

  • 看到这个线程。发送 x-www-form-urlencoded 时需要使用 URLSearchParams:stackoverflow.com/questions/41457181/…
  • 同样在await request() 中,await 没有任何用处。 await 只对承诺有用。如果您想要返回承诺的request() 版本,请参阅request-promise 模块。

标签: javascript node.js request axios


【解决方案1】:

您正在发送表单编码的数据:

headers:  {'content-type': 'application/x-www-form-urlencoded'},

...但是你将一个对象传递给 Axios:

data: {uname:'login', …

...所以 Axios 会将其编码为 JSON 而不是表单编码的数据。


the documentation:

默认情况下,axios 将 JavaScript 对象序列化为 JSON。要改为以 application/x-www-form-urlencoded 格式发送数据,您可以使用以下选项之一。

在node.js中,可以如下使用querystring模块:

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

【讨论】:

  • 我没有看到这个信息区。所以我改了,但是不行,结果是一样的……我已经用new FormData()测试过了,没有结果……
猜你喜欢
  • 1970-01-01
  • 2022-10-21
  • 2013-03-09
  • 1970-01-01
  • 2013-12-01
  • 2017-05-25
  • 2018-10-06
  • 1970-01-01
  • 2020-09-28
相关资源
最近更新 更多