【问题标题】:How to make sure headers that im passing to node-fetch request are correct?如何确保我传递给节点获取请求的标头是正确的?
【发布时间】:2020-05-10 17:13:40
【问题描述】:

我试图重写一个函数,该函数使用 request-promise 库基于节点获取来执行 get 请求:

这是 request-promise 中的方法:

import { default as request } from 'request-promise';

async function sendGet(cookies, url) {
  const options = {
    method: 'GET',
    uri: url,
    headers: {
      Accept: 'text/html,application/xhtml+xml,application/xml',
      'Upgrade-Insecure-Requests': '1',
      'Accept-Encoding': 'gzip, deflate, sdch, br',
      'Accept-Language': 'en-US,en;q=0.8',
      Host: 'some.url.com',
      Connection: 'keep-alive',
      cookie: cookies,
    },
    json: true,
    resolveWithFullResponse: true,
    simple: false,
    followRedirect: false,
  };
  try {
    const response = await request(getNextOptions);
    return {
      cookies: response.headers['set-cookie'],
      location: response.headers['location'],
    };
  } catch (e) {
    throw e;
  }
}

当更改为 node-fetch 时,它会给出以下错误响应:

“在此服务器上找不到请求的 URL /session/auth/failure。 此外,在尝试使用 ErrorDocument 处理请求时遇到 404 Not Found 错误。”

import fetch from 'node-fetch';

async function sendGet(cookies, url) {
  const headers = {
    'Upgrade-Insecure-Requests': '1',
    'Accept-Language': 'en-US,en;q=0.8',
    Host: 'some.url.com',
    Connection: 'keep-alive',
    cookie: cookies,
  }
  try {
    const result = await fetch(url, {
      headers,
      compress: true
    });
    const body = await result.json();

    return {
      cookies: body.headers.raw()['set-cookie'],
      location: body.headers.get('location'),
    };
  } catch (e) {
    throw e;
  }

我认为我通过的标头可能有问题,但经过几天的研究,我无法让它发挥作用。标题差异的一些解释:

  1. 我没有使用 Accept 标头,因为 node-fetch 默认添加 Accept: */*
  2. 而不是'Accept-Encoding': 'gzip, deflate, sdch, br' 我使用compression: true

提前感谢您的帮助!

【问题讨论】:

    标签: javascript node.js request-promise node-fetch


    【解决方案1】:

    您可以使用 https://requestbin.com/ 之类的东西来测试您的请求。

    基本上,您创建新的 Request BIN,然后使用 BIN url 而不是您的真实 url,然后查看您在那里请求的内容

    【讨论】:

    • 非常感谢这个提示!这允许我比较请求,但在标头中没有主机,因为它不允许我向 requestbin 发送请求。这表明请求完全相同,这使我开始更多地考虑标头中的主机。删除它后,我收到错误“达到最大重定向”,随后我注意到请求承诺版本 {followRedirect: false} 上的选项,所以剩下要做的就是在我的 fetch {redirect: 'manual'} 中添加选项,这解决了问题。再次感谢!
    • 我希望我知道请求 bin :)
    猜你喜欢
    • 2013-03-08
    • 2014-08-04
    • 2019-11-28
    • 2019-08-29
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多