javascript 如何确保im传递给节点获取请求的头是正确的?

w1jd8yoj  于 2023-03-21  发布在  Java
关注(0)|答案(2)|浏览(179)

我试图重写一个函数,它使用request-promise库来执行get请求,以基于node-fetch:
下面是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。另外,当尝试使用ErrorDocument来处理请求时遇到404错误。"*

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: */*
1.使用compression: true代替'Accept-Encoding': 'gzip, deflate, sdch, br' im
提前感谢您的帮助!

ffx8fchx

ffx8fchx1#

您可以使用类似https://requestbin.com/的代码来测试您的请求。
基本上,您创建了新的RequestBIN,然后使用BINurl而不是真实的的url,并查看您在那里请求的内容

oprakyz7

oprakyz72#

你可以开始监听本地服务器,使用netcat,比如nc -l 8080,然后向它发出请求。例如:
第一个终端:

$ nc -l 19990
GET /session/auth/failure HTTP/1.1
Host: localhost:19990
User-Agent: curl/7.68.0
a:b
content-type: application/json
Accept: text/html,application/xhtml+xml,application/xml
Upgrade-Insecure-Requests: 1
Accept-Encoding: gzip, deflate, sdch, br

第二端子:

$ curl -H "a:b" \
       -H "content-type: application/json" \
       -H "Accept: text/html,application/xhtml+xml,application/xml" \
       -H "Upgrade-Insecure-Requests: 1" \
       -H "Accept-Encoding: gzip, deflate, sdch, br" \ 
       http://localhost:19990/session/auth/failure

相关问题