我正在尝试用 jest 来模拟我的 azure 函数的节点获取。在测试中我有以下内容:
索引.test.ts
jest.mock("node-fetch");
import fetch from "node-fetch";
const {Response} = jest.requireActual("node-fetch");
// Setup code here...
const expectedResult: User = {
user_id: "1",
email: "testEmail@email.com",
name: "testUser",
nickname: "test",
picture: "pic",
app_metadata: {
email: "testEmail@email.com"
}
};
(fetch as jest.MockedFunction<typeof fetch>).mockReturnValue(new Response(JSON.stringify(expectedResult)));
Run Code Online (Sandbox Code Playgroud)
当我调用它时,我正在执行以下操作:
索引.ts
const options = {
method: 'PATCH',
headers: { "Content-Type": 'application/json', authorization: `Bearer ${accessToken}`},
body: body
};
const userResponse = await fetch(usersEndpoint, options);
const jsonResult = await userResponse.json();
context.res = {
body: jsonResult
}; …Run Code Online (Sandbox Code Playgroud) 我目前使用 request 在 node.js 中发出 http 请求。我在某个时候遇到了一个问题,我收到指示 UNABLE_TO_GET_ISSUER_CERT_LOCALLY 的错误。为了解决这个问题,它设置了rejectUnauthorized。我的请求工作代码如下所示:
var url = 'someurl';
var options = {
url: url,
port: 443,
// proxy: process.env.HTTPS_PROXY, -- no need to do this as request honors env vars
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
'Accept-Language': 'en-us',
'Content-Language': 'en-us'
},
timeout: 0,
encoding: null,
rejectUnauthorized: false // added this to prevent the UNABLE_TO_GET_ISSUER_CERT_LOCALLY error
};
request(options, function (err, resp, body) {
if (err) reject(err);
else resolve(body.toString());
});
Run Code Online (Sandbox Code Playgroud)
我想我会尝试使用 async/await …
我正在使用这个函数来调用外部API
const fetch = require('node-fetch');
fetchdata= async function (result = {}) {
var start_time = new Date().getTime();
let response = await fetch('{API endpoint}', {
method: 'post',
body: JSON.stringify(result),
headers: { 'Content-Type': 'application/json' },
keepalive: true
});
console.log(response)
var time = { 'Respone time': + (new Date().getTime() - start_time) + 'ms' };
console.log(time)
return [response.json(), time];
}
Run Code Online (Sandbox Code Playgroud)
问题是,我不确定每次使用此函数时,node.js 是否都会重用与 API 的 TCP 连接,尽管我定义了 keepalive 属性。
重用 TCP 连接可以显着提高响应时间
任何建议都将受到欢迎。
我正在使用node-fetchnpm 模块,并有一个辅助函数来向第三方服务发出授权请求(基本上只是用于添加授权标头的中间件)。
async function makeAuthorizedRequest(url: string, options: RequestInit) {
if (!options) {
options = { headers: {} as HeadersInit }
}
if (!options.headers) {
options.headers = {} as HeadersInit
}
options.headers.Authorization = `Bearer ${access_token}`
if (!options.headers['User-Agent']) {
options.headers['User-Agent'] = USERAGENT
}
return fetch(url, options)
}
Run Code Online (Sandbox Code Playgroud)
该RequestInit类型被定义为具有如下定义的headers类型属性HeadersInit
export type HeadersInit = Headers | string[][] | { [key: string]: string };
Run Code Online (Sandbox Code Playgroud)
我在 IDE (VSCode) 中遇到两个不同的错误,并tsc拒绝编译它,因为
Property 'Authorization' does not exist on type 'Headers'.ts(2339) …Run Code Online (Sandbox Code Playgroud) 我想通过 Flutter 调用 Cloud Functions 获取数据。
这是我的代码。
const functions = require("firebase-functions");
const admin = require('firebase-admin');
const fetch = require('node-fetch');
admin.initializeApp();
exports.postalCode = functions.https.onCall( (data, context) => {
const URL = 'https://zipcloud.ibsnet.co.jp/api/search?zipcode=100-0002';
return fetch(URL).then(res => res.json());
});
Run Code Online (Sandbox Code Playgroud)
错误 [ERR_REQUIRE_ESM]:必须使用 import 加载 ES 模块:/Users/xxx/node_modules/node-fetch/src/index.js
不支持 ES 模块的 require()。/Users/xxx/xxx/functions/index.js 中的 /Users/xxx/node_modules/node-fetch/src/index.js 的 require() 是一个 ES 模块文件,因为它是一个距离父包最近的 .js 文件。 package.json 包含 "type": "module" ,它将该包范围内的所有 .js 文件定义为 ES 模块。
相反,将 /Users/xxx/node_modules/node-fetch/src/index.js 重命名为以 .cjs 结尾,更改所需代码以使用 import(),或从 /Users/xxx/node_modules 中删除 "type": "module" /node-fetch/package.json。
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1102:13)
at …Run Code Online (Sandbox Code Playgroud) 我想在我的 NextJS 应用程序中显示 Google Place Photos。要从指定的 URL 获取这些图像,需要 API 密钥,但同时,我不想将此 API 密钥公开给公众。
我的目标是实现一个 NextJS API 路由,从 Google Places Photos 获取并返回指定的图像,同时还可以直接从图像标签访问,如下所示:
<img src={`/api/photos/${place?.photos[0].photo_reference}`} alt='' />
Run Code Online (Sandbox Code Playgroud)
我在网上发现了一些不同的来源,建议我将响应流从我的谷歌请求直接传输到传出响应的响应流,如下所示:
<img src={`/api/photos/${place?.photos[0].photo_reference}`} alt='' />
Run Code Online (Sandbox Code Playgroud)
然而,由于response.body是一个ReadableStream,它没有.pipe()函数。相反,它有 .pipeTo() 和 .pipeThrough()。
然后我尝试了
response.body.pipeTo(res);
Run Code Online (Sandbox Code Playgroud)
但是,这也不起作用,因为 res 是 NextApiResponse 而不是 WritableStream。虽然我在网上搜索过,但我还没有找到如何像WritableStreams那样写入NextApiResponse。
最后,我尝试手动将响应转换为缓冲区并将其写入 NextApiResponse,如下所示:
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const response = await fetch(
`https://maps.googleapis.com/maps/api/place/photo
&photo_reference=${id}
&key=${process.env.GOOGLE_PLACE_API_KEY}`,
);
if (!response.ok) {
console.log(response);
res.status(500).end();
return;
}
response.body.pipe(res);
}Run Code Online (Sandbox Code Playgroud)
虽然这完成了响应,但没有显示图像。
如何直接将检索到的谷歌地点图像从服务器传递到前端,以便标签可以使用它?
这就是我想要做的:我有一个由 webhook 触发的 lambda 函数,该函数将处理该数据并使用它向 api 发出 POST 请求。
我正在使用 Node.js 12 和 node-fetch 模块。
现在该函数已正确触发,但第一次调用时不会发送 POST。但如果我在短时间内重复触发 lambda 函数,第一个之后的请求就会通过。
以下是 lambda 函数的 index.js 文件中的代码:
const fetch = require('node-fetch');
exports.handler = async (event) => {
sendPost();
const response = {
statusCode: 200,
body: "Ok",
};
return response;
};
function sendPost() {
const url = "http://requestbin.net/r/vjv4mvvj";
const body = {
foo: "foo",
bar: "bar",
baz: "baz"
};
const params = {
method: "POST",
mode: "cors",
headers: {"Content-Type":"application/json"},
body: JSON.stringify(body)
};
fetch(url, params); …Run Code Online (Sandbox Code Playgroud) 问题是我正在尝试检索 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) 从这里复制:https : //github.com/node-fetch/node-fetch#json ...我的代码:
const fetch = require('node-fetch');
async function doFetch() {
const response = await fetch('https://api.github.com/users/github');
const data = await response.json();
console.log(data);
}
doFetch()
Run Code Online (Sandbox Code Playgroud)
错误信息——指的是fetch('https://...)调用:
This expression is not callable.
Type 'typeof import("[...]/node_modules/@types/node-fetch/index")' has no call signatures.
Run Code Online (Sandbox Code Playgroud)
我已经搜索过这个网站和其他网站,这个错误在许多模块中似乎很常见,尽管我只能找到使用import而不是require. 我猜这很简单,但我就是不知道如何用 require 语法解决这个问题。
我究竟做错了什么?提前致谢!
如果重要:JavaScript(不是 TypeScript)。节点.js。Mac 上的 VSCode。错误消息是由dbaeumer.vscode-eslint插件生成的。
我正在尝试使用 React 应用程序和 Webpack 设置来实现节点获取。但在使用节点获取时。我收到大量错误。
ERROR in node:buffer
Module build failed: UnhandledSchemeError: Reading from "node:buffer" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
at /mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/webpack/lib/NormalModule.js:832:25
at Hook.eval [as callAsync] (eval at create (/mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
at Object.processResource (/mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/webpack/lib/NormalModule.js:829:8)
at processResource (/mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/loader-runner/lib/LoaderRunner.js:220:11)
at iteratePitchingLoaders (/mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/loader-runner/lib/LoaderRunner.js:171:10)
at runLoaders (/mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/loader-runner/lib/LoaderRunner.js:398:2)
at NormalModule._doBuild (/mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/webpack/lib/NormalModule.js:819:3)
at NormalModule.build (/mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/webpack/lib/NormalModule.js:963:15)
at /mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/webpack/lib/Compilation.js:1371:12
at NormalModule.needBuild (/mnt/c/Users/nageshkatna/Desktop/frontend/node_modules/webpack/lib/NormalModule.js:1256:26)
ERROR in node:fs
Module build failed: …Run Code Online (Sandbox Code Playgroud) node-fetch ×10
node.js ×8
javascript ×6
fetch ×2
typescript ×2
asynchronous ×1
aws-lambda ×1
flutter ×1
http ×1
jestjs ×1
next.js ×1
oauth-2.0 ×1
reactjs ×1
require ×1
webpack ×1