标签: node-fetch

节点提取:禁用SSL验证

我有以下代码,这些代码是从快递服务器运行的:

import fetch from 'node-fetch';

let formBody = [];

const dataLogin = {
      'username': 'myUser',
      'password': 'myPassword'
};

for (let p in dataLogin) {
   let encodedKey = encodeURIComponent(p);
   let encodedValue = encodeURIComponent(dataLogin[p]);
   formBody.push(encodedKey + "=" + encodedValue);
 }

 formBody = formBody.join("&");   

 const url = 'https://external-login-api.com';
 return fetch(url, {
          method: 'POST',
          headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Content-Length': formBody.length         
  },     
  body: formBody
 });
Run Code Online (Sandbox Code Playgroud)

运行代码时,尽管能够在Postman中运行请求而没有问题,但仍收到以下错误。

{“消息”:“对https://external-login-api.com的请求失败,原因:编写EPROTO 7316:错误:141A318A:SSL例程:tls_process_ske_dhe:dh密钥太小:openssl \ ssl \ statem \ statem_clnt.c :1472:\ n“,”类型“:”系统“,” errno“:” EPROTO“,”代码“:” EPROTO“}

如何为此请求禁用SSL验证?

node.js node-fetch

4
推荐指数
2
解决办法
6618
查看次数

FetchError:无效的 json 响应正文

我正在使用 node-fetch 将一些 json 数据发送到 IFTTT 休息点。数据已成功发送到端点,但我的 NodeJS 控制台出现错误。如您所见,它返回 undefined 然后说有一个无效的 json 响应正文。我检查了身体,对我来说看起来很好。

问题是什么?

  async function checkTemperatureRange() {
    try {
      const temperatureSettings = await getTemperatureSetting();
      const currentTemperature = await getCurrentTemperature();

      if (currentTemperature < temperatureSettings.min_temp || currentTemperature > temperatureSettings.max_temp) {
        console.log('Temp NOT in range!');
        const body = { value1: currentTemperature };
        fetch('https://maker.ifttt.com/trigger/temp_reading/with/key/abc123', {
          method: 'post',
          body:    JSON.stringify(body),
          headers: { 'Content-Type': 'application/json' },
        })
        .then(function (res) {
          res.json()
        })
        .then(function (json) {
          console.log(json)
        })
        .catch(function (err) {
          console.log('node-fetch error: ', err)
        }); …
Run Code Online (Sandbox Code Playgroud)

node.js node-fetch

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

使用 require 时出现打字稿错误 - 该表达式不可调用。类型“typeof import(...)”没有调用签名.ts(2349)

我正在尝试运行这个脚本

const fetch = require('node-fetch');

function test() {
  fetch('https://google.com')
    .then(res => res.text())
    .then(text => console.log(text))
}

test();
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误

该表达式不可调用。类型 'typeof import("(...)/node_modules/node-fetch/@types/index")' 没有调用签名.ts(2349)

虽然当我使用 import 时它可以工作

import fetch from 'node-fetch';
Run Code Online (Sandbox Code Playgroud)

为什么以及如何解决它?

node.js typescript node-fetch

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

response.body.getReader 不是函数

我正在使用 fetch 调用 web api。我想将响应作为流读取,但是当我在 response.body 上调用 getReader() 时出现错误:“TypeError: response.body.getReader is not a function”。

  const fetch = require("node-fetch");
  let response = await fetch(url);
  let reader = response.body.getReader();
Run Code Online (Sandbox Code Playgroud)

typescript node-fetch

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

有没有办法记录节点获取请求?

所以我正在尝试使用node-fetch在 node.js 中使用一些 API,我想记录发送到服务器的最终请求,但我找不到任何方法来做到这一点。你能帮我吗?这是代码:

const fs = require('fs');
const fetch = require('node-fetch');
const https = require('https');


const reqUrl = 'https://endpoint.com';
const headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Digest': 'SHA-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=',
    'Date': 'Sat, 20 Mar 2021 15:42:18 GMT',
    'X-Request-ID': 'request_id',
    'Authorization': 'Bearer my_bearer',
    'Signature': 'my_signature'
};


const certs = {
    key: fs.readFileSync('path_to_key'),
    cert: fs.readFileSync('path_to_cert')
};

async function getAccounts() {
    const options = {
        cert: certs.cert,
        key: certs.key,
        rejectUnauthorized: false
    };

    const sslConfiguredAgent = new https.Agent(options);

    try {
        // here …
Run Code Online (Sandbox Code Playgroud)

javascript api fetch node.js node-fetch

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

如何正确用 fetch api 替换 axios api 并映射nodeJS中接收到的数据?

这是整个文件的链接 - asyncActions.js

带有 axios api 的部分 -

const fetchUsers = () => {
  return function (dispatch) {
    dispatch(fetchUsersRrequest());
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        // res.data is the array of users
        const users = res.data.map((user) => user.id);
        dispatch(fetchUsersSuccess(users));
      })
      .catch((error) => {
        // error.message gives the description of message
        dispatch(fetchUsersFaliure(error.message));
      });
  };
};
Run Code Online (Sandbox Code Playgroud)

函数输出 -

{ loading: true, users: [], error: '' }
{
  loading: false,
  users: [
    1, 2, 3, 4,  5,
    6, 7, 8, 9, 10
  ],
  error: …
Run Code Online (Sandbox Code Playgroud)

node.js reactjs redux fetch-api node-fetch

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

使用 promise 处理一组对象

我正在尝试制作一个 node express 应用程序,我从不同的 url 获取数据,调用 node-fetch 以提取某些页面的正文和有关某些 url 端点的其他信息。我想然后呈现一个 html 表以通过信息数组显示此数据。我在调用呈现信息时遇到问题,因为所有函数都是异步的,因此在调用呈现页面之前很难确保所有承诺调用都已解决。我一直在研究使用 bluebird 和 .finally() 和 .all() 的其他承诺调用,但它们似乎不适用于我的数据,因为它不是承诺调用数组,而是对象数组。每个对象是 4 个承诺调用,用于在一行中获取与我的表的一列相关的数据。

var express = require('express');
var fetch = require('node-fetch');
fetch.Promise = require('bluebird');
var router = express.Router();
const client = require('../platform-support-tools');


function makeArray() {
    var registry = client.getDirectory();

    var data_arr = [];
    for (var i = 0; i < registry.length; i++) {
        var firstUp = 0;
        for (var j = 0; i < registry[i]; j++) {
            if (registry[i][j]['status'] == 'UP') {
                firstUp …
Run Code Online (Sandbox Code Playgroud)

arrays promise javascript-objects node-fetch

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

如何修复 Typescript 编译错误 ts2345“缺少类型‘响应’......来自类型‘响应’:重定向、拖车、formData!”

我试图node-fetch在我的打字稿项目中提出请求,但我不明白如何修复编译错误或它实际上试图告诉我什么。

我已将所有包(包括全局打字稿包)更新到最新版本。

我创建了一个隔离错误的要点:https : //gist.github.com/HerrZatacke/ae90f608e042864b6e00e9c73a950602

这个(非常短的)脚本能够重现编译错误:

import fetch from 'node-fetch';

const toJson = (response: Response):PromiseLike<object> => (
  response.json()
);

const makeSomeRequest = (): Promise<object> => {
  return fetch('https://some-api.com/')
    .then(toJson)
};

makeSomeRequest();
Run Code Online (Sandbox Code Playgroud)

使用的安装版本是

@types/node-fetch 2.3.7
node-fetch2.6.0
typescript 3.5.2
Run Code Online (Sandbox Code Playgroud)

实际错误是

example.ts:9:11 - error TS2345: Argument of type '(response: Response) => PromiseLike<object>' is not assignable to parameter of type '(value: Response) => object | PromiseLike<object>'.
  Types of parameters 'response' and 'value' are incompatible.
    Type 'Response' is missing the following properties …
Run Code Online (Sandbox Code Playgroud)

node.js promise typescript node-fetch

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

TypeError: fetch 不是一个函数,我做错了什么?

我正在尝试使用node-fetch它来获取具有此 JSON 文件的网站,我可以将其用于我的不和谐机器人。

代码(JS):

const fetch = import("node-fetch")

// some code until

data = ""
        try {
            data = await fetch(`http://meme-api.herokuapp.com/gimme/${subreddit.toLowerCase()})}`).then(res => res.json)
            errored = false
        } catch (error) {
            throw error;
        }
Run Code Online (Sandbox Code Playgroud)

它错误地说:

TypeError: fetch is not a function
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

仅供参考,使用 require() 会导致错误,如下所示:

TypeError: fetch is not a function
Run Code Online (Sandbox Code Playgroud)

javascript node.js node-fetch

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

获取 VSCode 扩展:node-fetch 和 node:http 问题

我对 VSCode 扩展开发非常陌生。所以这可能是一个微不足道的问题或已经讨论过的问题。但我无法让它发挥作用。所以我正在寻求帮助。

我目前正在构建一个非常简单的扩展。使用命令托盘中的命令(假设:),Light Me Up它将显示随机引用作为信息消息。

这就是我想做的。我想从这里获取一堆报价,然后将它们存储在一个变量中,然后每次触发命令时我想选择一个随机报价并显示它。

这是我的代码看起来像

import * as vscode from 'vscode';
import fetch from 'node-fetch';
// const got = require('got');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
    
    console.log('Congratulations, your extension "seecode" is now active!');

    let data;

    (async () => {
        const response = await fetch("https://zenquotes.io/api/quotes");
        data = await response.json();
        console.log(data);
    })();

    context.subscriptions.push( …
Run Code Online (Sandbox Code Playgroud)

node.js typescript visual-studio-code vscode-extensions node-fetch

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