标签: node-fetch

Javascript节点获取同步获取

我正在尝试将node-fetch与nodejs结合使用以对我的个人api进行api调用。我希望能够在此期间定期同步更新某些值,因为在后台我的数据库会进行更新/更改。我知道异步和等待的存在,但我所有的谷歌搜索,我仍然不太了解它们或它们如何与获取请求交互。

这是我尝试开始工作的一些示例代码,但仍然只是未定义的日志

const fetch = require('node-fetch');
const url = 'http://example.com';
let logs;

example();
console.log(logs);
async function example(){
    //Do things here
    logs = await retrieveLogs();
    //Do more things here
}

async function retrieveLogs(){
    await fetch(url)
    .then(res => res.json())
    .then(json => {return json})
    .catch(e => console.log(e))
}
Run Code Online (Sandbox Code Playgroud)

javascript synchronous async-await node-fetch

6
推荐指数
2
解决办法
5764
查看次数

用开玩笑的方式模拟节点获取,创建一个用于模拟的响应对象

我正在尝试创建用于开玩笑的响应对象,我似乎无法获得正确的语法。

初始化,

jest.mock('node-fetch')
const fetch = require('node-fetch')
const { Response, Headers } = jest.requireActual('node-fetch')

// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
const meta = {
  'Content-Type': 'application/json',
  'Accept': '*/*',
  'Breaking-Bad': '<3'
}
// You can in fact use any iterable objects, like a Map or even another Headers
const headers = new Headers(meta)
const copyOfHeaders = new Headers(headers)

const ResponseInit = {
  status: 200,
  statusText: 'fail',
  headers: headers
}
Run Code Online (Sandbox Code Playgroud)

通过基本测试

  test('Basic Test', async () => {
    const token = ''
    const getDocList …
Run Code Online (Sandbox Code Playgroud)

unit-testing mocking node.js jestjs node-fetch

6
推荐指数
1
解决办法
4844
查看次数

使用绝对 url 前缀获取

大多数时候,我在fetchnode-fetch前面加上一个前缀http://localhost(使其成为绝对 URL)。

import fetch from 'node-fetch';

fetch('http://localhost/whatever')
Run Code Online (Sandbox Code Playgroud)

localhost除了简单地放入localhost变量之外,是否有任何方法可以避免该部分?

const baseUrl = 'http://localhost';

fetch(`${baseUrl}/whatever`)
Run Code Online (Sandbox Code Playgroud)

与具有绝对 url 前缀的 Superagent非常相关

absolute-path fetch node.js node-fetch

5
推荐指数
1
解决办法
3万
查看次数

在不指定maxSockets的情况下调用HTTP终结点时在Azure App Service上连接ETIMEDOUT

从Azure App Service中的node.js多次调用HTTP [S]终结点时,我遇到一些超时问题。

这里是我的代码来说明问题。

const fetch = require('node-fetch');
const https = require("https");
const agent = new https.Agent();

function doWork() {
  const works = [];
  for (let i = 0; i < 50; i++) {
    const wk = fetch('https://www.microsoft.com/robots.txt', { agent })
    .then(res => res.text())
    .then(body => console.log("OK", i))
    .catch((err) => console.log("ERROR", i, err));
    works.push(wk);
  }

  return Promise.all(works);
}

doWork()
.catch((err) => {
  console.log(err);
});
Run Code Online (Sandbox Code Playgroud)

在标准中型应用程序服务中运行此应用程序3或4次(我正在使用Kudu运行它,但我在标准网络应用程序中发现此错误)时,对于每个请求都会收到以下错误:

{ FetchError: request to https://www.microsoft.com/robots.txt failed, reason: connect ETIMEDOUT 23.206.106.109:443
    at ClientRequest.<anonymous> (D:\home\site\test\test-forge-calls\node_modules\node-fetch\lib\index.js:1393:11)
    at …
Run Code Online (Sandbox Code Playgroud)

azure node.js azure-web-sites azure-web-app-service node-fetch

5
推荐指数
0
解决办法
798
查看次数

Discord Oauth2 加入公会

const guildMembersResponse = fetch(`http://discordapp.com/api/guilds/440494010595803136/members/278628366213709824`,
            {
              method: 'PUT',
              headers: {
                Authorization: `Bearer TOKEN`,
              },
            });
            setTimeout(() => {
                console.log(guildMembersResponse)
            }, 500);
Run Code Online (Sandbox Code Playgroud)

我想使用他的用户 ID 和他在 nodejs 中的令牌将用户加入我的 Discord 服务器,但是如果我请求 Dicord api,我会收到一个错误:

Promise {
 Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: 
  null },
  [Symbol(Response internals)]:
  { url:
  'https://discordapp.com/api/guilds/440494010595803136/members/278628366213709824',
   status: 401,
   statusText: 'UNAUTHORIZED',
   headers: [Headers] } } }
Run Code Online (Sandbox Code Playgroud)

我正在使用node-fetch库!

node.js oauth-2.0 express discord node-fetch

5
推荐指数
1
解决办法
7587
查看次数

apollo 网关仅支持 HTTP(S) 协议

我正在尝试使用 apollo 托管解决方案中的托管配置在本地运行 apollo 网关。它加载架构并且一切都很好,但是当我在 Playground 中尝试查询时,我得到“仅支持 HTTP(S) 协议”。我知道我可以使用 serviceList,但我希望能够使用 apollo 图管理器在 POC 本地运行它。这似乎是阿波罗使用的节点获取的问题,因为它甚至没有调用底层数据源并且在网关处失败。

在此输入图像描述

/* istanbul ignore file */
import {ApolloServer} from 'apollo-server';

import {ApolloGateway} from '@apollo/gateway';

 const {
   NODE_ENV,
 } = process.env;


 const gateway: ApolloGateway = new ApolloGateway();

 const main = async () => {
    return new ApolloServer({
        gateway,
        playground: NODE_ENV !== 'production',
        subscriptions: false,
 });
}

export default main;
Run Code Online (Sandbox Code Playgroud)

我在网上到处搜索,似乎找不到答案,所以任何帮助将不胜感激。有什么想法如何让它在本地工作吗?提前致谢。

node.js graphql apollo-server node-fetch apollo-federation

5
推荐指数
1
解决办法
2191
查看次数

如何配置 node-fetch 使用公司代理?

我正在执行需要从第三方 api 获取结果的独立 nodejs 脚本(不涉及 Web 服务器)。该程序使用 'node-fetch' 来执行 fetch(url) 并且我从命令行使用它运行它node .\test.js

当我连接到我们公司的网络时失败,但在直接互联网上工作正常。我已经在 npm 中配置了代理设置,可以看到它npm config ls显示了代理和 https-proxy 的正确值。

所以问题是: 1. 通过节点运行 test.js 是否不从 npm 中选择代理配置?2. 如何确保fetch(url)调用通过我们的代理?

提前致谢

node.js node-fetch

5
推荐指数
1
解决办法
1万
查看次数

Axios 和 fetch 响应来自同一外部端点的不同状态代码

我正在尝试向此端点发送请求:https://9gag.com/v1/group-posts/group/default/type/trending获取 9gag 帖子数据。

在邮递员和 chrome 上运行良好,但是当我尝试axios从 Node.js使用时,它响应403(并读取返回的 DOM,它认为它要求我输入验证码),当我尝试使用 发送请求时node-fetch,它响应与200帖子数据(这是正确的)。

问题是,为什么node-fetch工作正常但axios没有?

这是我用于测试的代码:

import axios from "axios";
import fetch from "node-fetch";

const URL = "https://9gag.com/v1/group-posts/group/default/type/trending";

// Inside async function
await fetch(URL); // Responded with 200 and json data
await axios(URL); // Responded with 403 and HTML DOM, axios.get() also gives the same result
Run Code Online (Sandbox Code Playgroud)

javascript node.js fetch-api axios node-fetch

5
推荐指数
1
解决办法
227
查看次数

node-fetch@3 在 Nestjs 中不支持,因为它是 ESM

我无法使用包“node-fetch@3”。我只需导入它,我的控制台就会记录错误:

const node_fetch_1 = require("node-fetch");
                     ^
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/control-panel-nest2/node_modules/node-fetch/src/index.js from /home/control-panel-nest2/dist/bimwize/document.service.js not supported.
Instead change the require of index.js in /home/control-panel-nest2/dist/bimwize/document.service.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/home/control-panel-nest2/dist/bimwize/document.service.js:19:22)
    at Object.<anonymous> (/home/control-panel-nest2/dist/bimwize/bimwize.module.js:14:28)
    at Object.<anonymous> (/home/control-panel-nest2/dist/user/user.module.js:11:26)
    at Object.<anonymous> (/home/control-panel-nest2/dist/app.module.js:17:23)
    at Object.<anonymous> (/home/control-panel-nest2/dist/main.js:6:22)
Run Code Online (Sandbox Code Playgroud)

我知道发生了什么事。node-fetch@3 仅支持 esm,但不支持 commonjs,nestjs 会将我所有的导入编译为 require。

我不知道如何解决这个问题。我尝试使用node-fetch@2,但node-fetch@2缺少一些我想要的功能。

node-fetch nestjs

5
推荐指数
1
解决办法
3629
查看次数

如何将 Node-fetch 与 Jest 和 Typescript 结合使用?

我正在尝试设置一个非常简单的 NPM 代码库,我可以用它来驱动 API 来进行一些测试。

\n

导致错误的代码行只是import fetch from "node-fetch";,请参阅代码

\n

对于设置/配置,我正在关注此存储库(建议使用更好的模板将不胜感激):https://github.com/bromix/typescript-jest-example

\n

node-fetch当我尝试在代码中使用该库(在目录test.ts中的文件/test或目录.ts中的文件中/src)时,出现以下错误:

\n
FAIL  test/Api.test.ts\n  \xe2\x97\x8f Test suite failed to run\n\n    Jest encountered an unexpected token\n\n    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.\n\n...\n\n    Details:\n\n    C:\\ardc\\rats\\node_modules\\node-fetch\\src\\index.js:9\n    import http from \'node:http\';\n    ^^^^^^\n\n    SyntaxError: Cannot …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs es6-modules node-fetch ts-jest

5
推荐指数
1
解决办法
6117
查看次数