【问题标题】:Difference between Postman and a simple Http Request with superagentPostman 和带有 superagent 的简单 Http 请求之间的区别
【发布时间】:2017-12-05 19:21:18
【问题描述】:

我想知道使用 superagent 的简单 POST 请求和使用 Postman 的 POST 请求有什么区别。 因为我试图废弃一个网站,所以我向 Postman 发出了一个发布请求,一切正常,我得到了预期的结果。但是当我使用 superagent 进行 POST Http 请求时,我得到了 301 重定向。

有没有办法通过与 Postman 相同的结果来解决这个问题?

提前感谢您的回答。

【问题讨论】:

  • Paul,请将您的代码添加到 StackOverflow 上的下一个问题中。

标签: javascript node.js postman http-status-code-301 superagent


【解决方案1】:

您应该使用redirects。简单例子:

const request = require('superagent');
const url = 'localhost:3000/example';
request
.post(url)
.send({msg: "hello"})
.redirects(1) //Add redirect functionality
.on('redirect', function(res) {
  console.log('Redirected');
})
.end(function(err, res){
  console.log(res);
})

【讨论】:

    【解决方案2】:

    我不知道,但看起来邮递员遵循 301(永久移动),而您的超级代理不是。 301 是重定向响应。见details

    通常您应该在代码中处理 301 响应。在响应中,您将找到重定向的 URL。

    【讨论】:

      【解决方案3】:

      在邮递员中,如果它收到 HTTP 301 响应,如果您没有看到 301 响应,并且您在重定向后收到实际响应,它将自动重定向,但在超级代理中,它不会自动重定向,您会看到 301 响应。

      您可以在邮递员中启用拦截器以禁用自动重定向。

      大多数网站使用此标头告诉浏览器它应该重定向,例如在某些网站中,如果您调用 http://target.com 它会得到 301 响应并重定向到 https://target.com

      【讨论】:

        【解决方案4】:

        谢谢大家的回答,我可能发现了我的问题:实际上是服务器等待 application/x-www-form-urlencoded 格式。

        如何在 superagent HTTP 请求中翻译这个? 我试过了:

        postData() {
            return new Promise((resolve, reject) => {
            request
                    .post(this.url)
                    .send('destinations={"1": "testa"}')
                    .send('stopId=2643')
                    .send('lineId=1150')
                    .send('sens=2')
                    .end((err, res) => {
                    if (err) reject(err);
                    resolve(res)
                })
            })
        }
        

        好的,我找到了解决方案,对于其他人,我在上面发布了这个:

        request
                .post(this.url)
                .set('Content-Type', 'application/x-www-form-urlencoded')
                .send({destinations: '{"1":"test"}'})
                .send({stopId: "2643"})
                .send({lineId: "1150"})
                .send({sens: "2"})
                .end(function(err, res){
                 console.log(res);
              })
        

        【讨论】:

          猜你喜欢
          • 2020-01-08
          • 2012-10-24
          • 2016-04-22
          • 1970-01-01
          • 1970-01-01
          • 2016-10-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多