我正在尝试在我的节点 js 代码中使用 node-fetch 向外部 API 发布请求。
如果在执行 POST 请求时出现任何超时或网络故障,我想重试该请求 3 次。
你能告诉我如何使用 node-fetch 重试请求吗?我看到有一个 npm 模块https://www.npmjs.com/package/node-fetch-retry但它似乎没有按预期工作,而且它也不接受重试之间的重试间隔。任何代码片段都会非常有帮助。
编辑:
谢谢我尝试使用 promise-fn-retry 但它似乎没有做任何重试。下面是我通过关闭 WIFI 然后执行 FETCH 调用以查看它是否重试 3 次而尝试的代码片段。但它只执行一次获取并返回错误。
const promiseFn = () => fetch(url,{method:"POST",headers:header,body:JSON.stringify(payload)});
const options = {
times: 3,
initialDelay: 100,
onRetry: (error) => {
console.log(error);
}
};
console.log('PromiseFn result ****'+retry(promiseFn, options).then(res => res.json()).then((res)=>{console.log('Promise Fn result is'+JSON.stringify(res))}).catch((err)=>{console.log('Error in Promise Fn'+err)}));
Run Code Online (Sandbox Code Playgroud) 我是 Node.js 和 API 的新手,所以我希望有人能提供帮助!我正在尝试使用 node-fetch 从幻想英超联赛 API 获取 JSON 数据。我已在客户端中成功完成此操作,但从我的 node.js 服务器文件中我不断收到错误:
UnhandledPromiseRejectionWarning:FetchError: https://fantasy.premierleague.com/api/entry/3/处的 json 响应正文无效原因:JSON 输入意外结束
响应本身的状态为 200,但大小为 0,因此它不返回任何数据。我知道它应该可以工作,因为当您访问 url 时 JSON 是清晰可见的,并且我已经可以在客户端代码中使用 fetch 了。
这是我正在使用的代码:
const fetch = require('node-fetch');
async function fetchEntry() {
const api_url = 'https://fantasy.premierleague.com/api/entry/3/';
const fetchEntry_response = await fetch(api_url);
const json = await fetchEntry_response.json();
console.log("json: " + JSON.stringify(json));
};
fetchEntry();
Run Code Online (Sandbox Code Playgroud)
注意:在客户端代码上,我遇到了 CORS 错误,因此需要使用代理(https://thingproxy.freeboard.io/fetch/https://fantasy.premierleague.com/api/entry/3/)让它发挥作用。我不确定这是否相关?
任何帮助将不胜感激!
乔
我正在使用Express JS server来执行AWS MWS API. 根据MWS文档,_GET_REMOTE_FULFILLMENT_ELIGIBILITY_返回 Excel 文件对象。
我创建了 API,node js但无法获得正确的 excel。我在下载的 Excel 文件中出现了奇怪的字符。
const getRemoveFulfillmentEligibilityDataCon = async(req,res) => {
const mwsRequestData = {
Version: '2009-01-01',
Action: 'GetReport',
'SellerId': 'MWS_SELLER_ID',
'MWSAuthToken': 'MWS_AUTH_TOKEN',
ReportId: 'XXXXXXXXXXXXXX',
};
try {
const response = await amazonMws.reports.search(mwsRequestData);
/* make the worksheet */
var ws = XLSX.utils.json_to_sheet(response.data);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws);
XLSX.writeFile(wb, "sheetjs.xlsx");
return response;
} catch (error) {
console.log('error ', error);
return …Run Code Online (Sandbox Code Playgroud) 尝试学习,JavaScript。请原谅,如果这真的是一个基本的薄我想念。
我试图运行node-fetch到错误的URL,我希望应该捕获该错误并记录我的相应消息。但是,当我通过节点运行此文件时,它给了我未捕获的错误
const fetch = require('node-fetch');
fetch('http://api.icnd.com/jokes/random/10')
.then(response => {
response.json().then((data) => {
console.log(data)
});
}).
catch(error => {
console.log('There is some error');
});
(node:864) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at http://api.icnd.com/jokes/random/10 reason: Unexpected token < in JSON at position 0
at /Users/raheel/code/js-tutorial/node_modules/node-fetch/lib/index.js:254:32
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
(node:864) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled …Run Code Online (Sandbox Code Playgroud) 我在模块中定义了一个函数,该函数应该执行获取并返回响应。我在从 fetch 返回响应时遇到问题。调用函数将返回值设为“未定义”。
我是 JavaScript 和 Node 的新手,所以如果你不介意的话,可能需要一点帮助。
调用函数
async function executeTest() {
try {
const response = await bpc.postLendingApplication(
blendConnection,
loanData
);
console.log("Response from POST Loan: ", response);
} catch (error) {
console.log(error);
}
}
Run Code Online (Sandbox Code Playgroud)
执行获取请求的模块函数
const fetch = require("node-fetch");
async function postLendingApplication(connection, data) {
console.log("Processing POST Loan.");
await fetch(connection.url, {
method: "POST",
headers: connection.headers,
body: data,
}).then(async res => {
console.log("Status: ", res.status);
console.log("StatusText: ", res.statusText);
console.log("OK: ", res.ok);
return await res;
});
}
Run Code Online (Sandbox Code Playgroud)
控制台输出是:
Processing POST Loan. …Run Code Online (Sandbox Code Playgroud) 我正在尝试迁移到 S3,现在我通过 URL 向其他主机提供图像,我可以下载它,在使用时更改它的大小(以节省大小并更快地提供它们),然后将其上传到 S3在我的机器上保存副本吗?
根据node-fetch文档node-fetch
我们可以得到这样的响应状态
fetch('https://github.com/')
.then(res => {
console.log(res.status);
});
Run Code Online (Sandbox Code Playgroud)
并获取数据
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(jsonData => console.log(jsonData));
Run Code Online (Sandbox Code Playgroud)
我有一个场景,我需要从响应中返回JSON数据和状态.我试着这样用
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(jsonData => {
console.log(jsonData);
console.log(jsonData.status);
});
Run Code Online (Sandbox Code Playgroud)
但是
执行console.log(jsonData.status)
不会返回状态.我如何获得状态和输出数据
我需要https使用node.js 对某些请求禁用对等SSL验证node-fetch,据我所知,现在我使用的包没有该选项。
那应该是CURL的 CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false
是否有任何联网软件包都允许这样做?有没有一种方法可以跳过axios中的SSL验证?
连接 API 时,我收到了可怕的 CORS 错误。我正在使用 BeerDB 之一。我尝试了该插件,添加标题,进入index.js但似乎没有解决它。仍在研究它,我的代码App.js如下。这是一个反应应用程序。
我什至可以想到的下一件事是重构我的 API 获取调用以使用axios和使用与当前使用的语法不同的语法。
import React, {useEffect, useState, Component} from 'react';
import './App.css';
import Beer from './Beer.js';
const App = () => {
const App_Key = "b1322de05886eaf6bdd71b64c52d12b7"
const [beers, setBeers] = useState([]);
useEffect (() => {
getBeers();
}, []);
const getBeers = async () => {
const response = await fetch("http://api.brewerydb.com/v2/?key=b1322de05886eaf6bdd71b64c52d12b7");
const data = await response.json();
console.log(data);
}
return(
<div className="App">
<form>
<input type="text" ></input>
<button type="submit">Search</button>
</form> …Run Code Online (Sandbox Code Playgroud) node-fetch ×9
node.js ×7
javascript ×5
fetch ×2
amazon-mws ×1
amazon-s3 ×1
async-await ×1
axios ×1
cors ×1
ecmascript-6 ×1
express ×1
fetch-api ×1
reactjs ×1
sharp ×1