标签: node-fetch

通过 Node-Fetch 检索 OAuth2 令牌

问题是我正在尝试检索 OAuth2 令牌。由于request已被弃用,我正在使用node-fetch它。虽然我可以让它工作request,但我不能node-fetch

我在这里读过很多帖子,但似乎没有一个真正给出了真正有效的一致答案。我承认我只是看起来不够好。我将其包装在测试中也可能会变得复杂,但由于我收到的错误消息,感觉情况并非如此。

以下是有效的代码(请注意,我必须更改详细信息以保护内部 URL):

var request = require("request");

var options = {
  method: "POST",
  url: "https://some-url/realms/my-realm/protocol/openid-connect/token",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  form: {
    username: "JeffUser",
    password: "jeff-password",
    grant_type: "password",
    client_id: "jeff-client",
    client_secret: "jeff-client"
  }
};

request(options, function(error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
})

Run Code Online (Sandbox Code Playgroud)

这有效,我得到了令牌。这是我正在尝试的node-fetch(包含在测试中)失败的内容:

const assert = require("chai").assert;
const fetch = require("node-fetch")

describe("Test API", function() {
  let api_token = "";

  it("gets a token", async …
Run Code Online (Sandbox Code Playgroud)

javascript oauth-2.0 node-fetch

7
推荐指数
1
解决办法
7652
查看次数

节点使用Graphql查询获取发布请求

我正在尝试使用GraphQL查询发出POST请求,但它返回错误Must provide query string,即使我的请求在PostMan中有效.

以下是我在PostMan中运行它的方法:

在此输入图像描述

在此输入图像描述

这是我在我的应用程序中运行的代码:

const url = `http://localhost:3000/graphql`;    
return fetch(url, { 
  method: 'POST',
  Accept: 'api_version=2',
  'Content-Type': 'application/graphql',
  body: `
    {
      users(name: "Thomas") { 
        firstName
        lastName 
      } 
    }
  `
})
.then(response => response.json())
.then(data => {
  console.log('Here is the data: ', data);
  ...
});
Run Code Online (Sandbox Code Playgroud)

我有什么想法我做错了吗?是否有可能使我将fetch请求传入的body属性格式化为Text我在PostMan请求的主体中指定的格式?

javascript node.js express graphql node-fetch

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

将 NodeJS 流消耗到缓冲区和写入流的正确方法

我需要将可读流通过管道传输到缓冲区(要转换为字符串)和文件中。流来自node-fetch.

NodeJS 流有两种状态:暂停和流动。据我了解,一旦'data'附加了侦听器,流就会更改为流动模式。我想确保我读取流的方式不会丢失任何字节。

方法 1:管道并读取'data'

fetch(url).then(
  response =>
    new Promise(resolve => {
      const buffers = []
      const dest = fs.createWriteStream(filename)
      response.body.pipe(dest)
      response.body.on('data', chunk => buffers.push(chunk))
      dest.on('close', () => resolve(Buffer.concat(buffers).toString())
    })
)
Run Code Online (Sandbox Code Playgroud)

方法2:使用直通流:

const { PassThrough } = require('stream')
fetch(url).then(
  response =>
    new Promise(resolve => {
      const buffers = []
      const dest = fs.createWriteStream(filename)
      const forFile = new PassThrough()
      const forBuffer = new PassThrough()
      response.body.pipe(forFile).pipe(dest)
      response.body.pipe(forBuffer)
      forBuffer.on('data', chunk => buffers.push(chunk))
      dest.on('close', () => resolve(Buffer.concat(buffers).toString())
    }) …
Run Code Online (Sandbox Code Playgroud)

stream node.js node-fetch

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

节点获取连接 ETIMEDOUT 错误

我试图获取 200 状态代码作为响应,但结果是 ETIMEDOUT。我无法理解,我怎么可能通过postman获取成功的响应,但总是通过节点获取以 ETIMEDOUT 响应来获取相同的响应。这是代码示例:

const Resource = {
  get: cb => {
    fetch('https://example.com', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: {...some body...},
    }).then(res => {
      if (res.status !== 200) cb(`Status: ${res.status}, ${res.statusText}`)
      return res.text()
    }).then(data => {
        cb(null, data)
      }).catch((err) => {
       console.log('ERROR: ', err)
      })
  }
}
Run Code Online (Sandbox Code Playgroud)

这是回应:

ERROR: { FetchError: request to https://example.com failed, reason: connect ETIMEDOUT at ClientRequest.<anonymous> (C:\Users\projects\DSSRQ\node_modules\node-fetch\lib\index.js:1393:11) at emitOne (events.js:116:13) at ClientRequest.emit (events.js:211:7) at TLSSocket.socketErrorListener (_http_client.js:387:9) at emitOne (events.js:116:13) …

javascript node.js node-fetch

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

服务器上的节点获取请求失败:无法获取本地颁发者证书

〜我正在使用Node 10.9.0和npm 6.2.0〜

我正在运行以下应用程序,该应用程序使我能够一遍http又一遍地向同一站点发出请求https

var fetch = require('node-fetch')
const express = require('express')
const app = express()

//-- HTTP --
app.get('/test-no-ssl', function(req, res){
  fetch('http://jsonplaceholder.typicode.com/users')
  .then(res => res.json())
  .then(users => {
    res.send(users)
  }).catch(function(error) {
    res.send(error)
  })
})

//-- HTTPS --
app.get('/test-ssl', function(req, res){
  fetch('https://jsonplaceholder.typicode.com/users')
  .then(res => res.json())
  .then(users => {
    res.send(users)
  }).catch(function(error) {
    res.send(error)
  })
})

app.listen(3003, () => 
  console.log('Listening on port 3003...')
)
Run Code Online (Sandbox Code Playgroud)

两者在我的本地计算机上都可以正常工作,并返回Typicode提供的JSON响应。但是,当我将它们作为Node应用程序部署到Web主机(FastComet)上时,会得到以下结果:

HTTP- /test-no-ssl按预期返回JSON

HTTPS- /test-ssl返回以下错误:

{ 
  "message" : "request to …
Run Code Online (Sandbox Code Playgroud)

ssl node.js express node-fetch

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

如何知道我将被重定向到的网址?[nodejs] [节点获取]

我正在尝试从谷歌云中的网址加载 JSON 文件。我正在使用 node-fetch 包,它可以正常工作几个小时。问题是谷歌经常更改重定向的网址。如何向我将转发到的 url 发出 get 请求?或者至少知道我将被转发到哪个网址?我看到还有一个名为 request 的包,但它已被弃用。

这是代码

var express = require('express');
var router = express.Router();
var fetch = require('node-fetch');

router.get('/', async (req, res) => {
  
  const url = 'https://storage.cloud.google.com/blablabla/config.json';

  fetch(url)
    .then((res) => {
      if (res.ok) {
        return res.json();
      }
    })
    .then((data) => res.send({ data }))
    .catch((err) => res.send(err));
});

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

redirect http-redirect node.js node-fetch

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

节点获取将帖子正文作为表单数据发送

我正在尝试发送带有正文的 POST 请求,form-data因为这似乎是唯一有效的方法。

我也在邮递员中尝试过此操作,但发送body不起作用raw JSON

所以我尝试做同样的事情,node-fetch但似乎body正在发送,JSON并且我得到了与以前相同的错误(当raw从邮递员使用时)。

try{
  const { streamId } = request.body;
  const headers = {        
    "Authorization": INO_AUTHORIZATION_CODE,
    // "Content-Type": "multipart/form-data; boundary=<calculated when request is sent>"
    "Content-Type": "application/json"
  }      
  const url = `https://www.inoreader.com/reader/api/0/stream/contents/${streamId}`;
  const body = {
      AppId: INO_APP_ID,
      AppKey: INO_APP_KEY
  }
  
  const resp = await fetch(url, {
      method: 'POST',
      body: JSON.stringify(body),
    //   body: body,
      headers: headers
    });   
    
  const json = await resp.text();
  return response.send(json); …
Run Code Online (Sandbox Code Playgroud)

post node.js postman node-fetch

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

const fetch = require("node-fetch"); ^ 错误 [ERR_REQUIRE_ESM]:ES 模块的 require()

我有一个问题,我对编程一无所知,我想制作一个 nft 集合,我正在关注这个 YouTube 视频:https://www.youtube.com/watch ?v=AaCgydeMu64

\n

一切都很顺利,直到 (32:14) 左右\n我的文本与视频中的文本相同,所以我不明白发生了什么。\n当我运行命令时:node utils/nftport/uploadFile.js

\n

它说:

\n
const fetch = require("node-fetch");\n              ^\n\nError [ERR_REQUIRE_ESM]: require() of ES Module ......\\hashlips_art_engine-main\\node_modules\\node-fetch\\src\\index.js from ......\\hashlips_art_engine-main\\utils\\nftport\\uploadFile.js not supported.\nInstead change the require of index.js in ......\\hashlips_art_engine-main\\utils\\nftport\\uploadFile.js to a dynamic import() which is available in all CommonJS modules.\n    at Object.<anonymous> ......\\hashlips_art_engine-main\\utils\\nftport\\uploadFile.js:2:15) {\n  code: ?[32m\'ERR_REQUIRE_ESM\'?[39m\n
Run Code Online (Sandbox Code Playgroud)\n

注意!:(......) 只是对应该存在的文件的写入替换

\n

这是 uploadFile.js 的代码:

\n
const FormData = require("form-data");\nconst fetch = require("node-fetch");\nconst basePath = process.cwd();\nconst fs = require("fs");\n\nfs.readdirSync(`${basePath}/build/images`).forEach((file) => {\n    const formData = …
Run Code Online (Sandbox Code Playgroud)

node.js node-fetch

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

节点获取:不支持的 URL 类型“节点:”:节点:缓冲区

我需要让Node-fetch为 VUE JS 项目工作,但我遇到了这些依赖项错误:

These dependencies were not found:

* node:buffer in ./node_modules/node-fetch/src/index.js, ./node_modules/node-fetch/src/body.js
* node:http in ./node_modules/node-fetch/src/index.js, ./node_modules/node-fetch/src/headers.js
* node:https in ./node_modules/node-fetch/src/index.js
* node:net in ./node_modules/node-fetch/src/utils/referrer.js
* node:stream in ./node_modules/node-fetch/src/index.js, ./node_modules/node-fetch/src/body.js
* node:url in ./node_modules/node-fetch/src/request.js
* node:util in ./node_modules/node-fetch/src/body.js, ./node_modules/node-fetch/src/headers.js and 1 other
* node:zlib in ./node_modules/node-fetch/src/index.js

To install them, you can run: npm install --save node:buffer node:http node:https node:net node:stream node:url node:util node:zlib
Run Code Online (Sandbox Code Playgroud)

我尝试run npm install --save node:buffer node:http node:https node:net node:stream node:url node:util node:zlib …

node.js node-fetch

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

Node标准https和node-fetch在提供证书时的区别

ADP 的 REST API 要求每次请求时都发送 SSL 证书和私钥。

当我使用“标准 Node.js HTTP(S) 模块”时:

require('dotenv').config()

const fs = require('fs')
const path = require('path')

const certificate_path = path.resolve('../credentials/certificate.pem')
const private_key_path = path.resolve('../credentials/private.key')

const options = {
    hostname: 'api.adp.com',
    path: '/hr/v2/workers/ABCDEFGHIJKLMNOP',
    method: 'GET',
    headers: {
        'Accept': 'application/json;masked=false',
        'Authorization': `Bearer ${process.env.ACCESS_TOKEN}`
    },
    cert: fs.readFileSync(certificate_path, "utf8"),
    key: fs.readFileSync(private_key_path, "utf8"),
};

require('https').get(options, res => {

  let data = [];

  res.on('data', chunk => {
    data.push(chunk);
  });

  res.on('end', () => {

    const workers = JSON.parse(Buffer.concat(data).toString());

    for(worker of workers.workers) {
      console.log(`Got …
Run Code Online (Sandbox Code Playgroud)

javascript client-certificates node.js node-https node-fetch

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