我正在尝试制作一个Discord机器人,它只会显示是否有人在线玩游戏。
然而我不断收到这样的消息:
[ERR_REQUIRE_ESM]:不支持 ES 模块的 require()。相反,将index.js in... 的 require 更改为动态 import(),该动态 import() 在所有 CommonJS 模块中都可用。
这是我的代码:
module.exports = {
name: 'username',
description: "this is the username command",
async execute(message, args) {
const fetch = require('node-fetch');
if (args.length !== 1) {
return message.channel.send("invalid username wtf")
}
const ign = args[0]
if (ign.length > 16 || ign.length < 3) {
return message.channel.send("invalid username wtf")
}
const uuid = await fetch(`https://api.mojang.com/users/profiles/minecraft/${ign}`).then(data => data.json()).then(data => data.id).catch(err => message.channel.send("error wtf"));
const onlineInfo = …Run Code Online (Sandbox Code Playgroud) 我正在创建一个程序来分析安全摄像头流,但卡在了第一行。目前,我的 .js 文件除了导入 node-fetch 之外什么都没有,它给了我一条错误消息。我究竟做错了什么?
在适用于 Linux 的 Windows 子系统中运行 Ubuntu 20.04.2 LTS。
节点版本:
user@MYLLYTIN:~/CAMSERVER$ node -v
v14.17.6
Run Code Online (Sandbox Code Playgroud)
节点获取包版本:
user@MYLLYTIN:~/CAMSERVER$ npm v node-fetch
node-fetch@3.0.0 | MIT | deps: 2 | versions: 63
A light-weight module that brings Fetch API to node.js
https://github.com/node-fetch/node-fetch
keywords: fetch, http, promise, request, curl, wget, xhr, whatwg
dist
.tarball: https://registry.npmjs.org/node-fetch/-/node-fetch-3.0.0.tgz
.shasum: 79da7146a520036f2c5f644e4a26095f17e411ea
.integrity: sha512-bKMI+C7/T/SPU1lKnbQbwxptpCrG9ashG+VkytmXCPZyuM9jB6VU+hY0oi4lC8LxTtAeWdckNCTa3nrGsAdA3Q==
.unpackedSize: 75.9 kB
dependencies:
data-uri-to-buffer: ^3.0.1 fetch-blob: ^3.1.2
maintainers:
- endless <jimmy@warting.se>
- bitinn <bitinn@gmail.com>
- timothygu <timothygu99@gmail.com>
- akepinski <npm@kepinski.ch>
dist-tags: …Run Code Online (Sandbox Code Playgroud) 我只是用
const fetch = require('node-fetch')
Run Code Online (Sandbox Code Playgroud)
我得到
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\Alex\Desktop\rollbot\node_modules\node-fetch\src\index.js from C:\Users\Alex\Desktop\rollbot\index.js not supported.
Instead change the require of C:\Users\Alex\Desktop\rollbot\node_modules\node-fetch\src\index.js in C:\Users\Alex\Desktop\rollbot\index.js to a
dynamic import() which is available in all CommonJS modules.
{
code: 'ERR_REQUIRE_ESM'
}
Run Code Online (Sandbox Code Playgroud)
我的所有其他包都可以工作,只有 node-fetch 可以做到这一点。为了使用node-fetch,我应该做什么?
我正在尝试升级我的 api 以使用 node-fetch 3.0.0。他们的文档中的部分重大更改是,node-fetch 现在是一个纯粹的 ESM 模块。
\nhttps://github.com/node-fetch/node-fetch/blob/main/docs/CHANGELOG.md
\n我的单元测试已经开始突破这个变化。我使用 jest.requireActual("node-fetch") 作为 Response 对象
\nconst { Response } = jest.requireActual("node-fetch");\nRun Code Online (Sandbox Code Playgroud)\n然而,随着新的变化,我得到:
\n“类型 \'{}\' 上不存在属性 \'Response\'。”
\n我尝试更改为 import 语句,这似乎可以修复该错误:
\nimport { Response } from "node-fetch"\nRun Code Online (Sandbox Code Playgroud)\n现在,当我运行单元测试时,出现以下错误:
\nTest suite failed to run\n \n Jest encountered an unexpected token \n \n This usually means that you are trying to import a file which Jest cannot parse, e.g. it\'s not plain JavaScript. \n \n By …Run Code Online (Sandbox Code Playgroud) 我开始在我的 nodejs 项目中使用 Typescript。为了访问一些外部 API,我使用 node-fetch 来发出请求。在设置 PUT 请求时,会弹出一个错误,说给定的主体不可分配给 type RequestInit:
错误:
Error:(176, 28) TS2345:Argument of type '{ headers: Headers; method: string; body: MyClass; }' is not assignable to parameter of type 'RequestInit'.
Types of property 'body' are incompatible.
Type 'MyClass' is not assignable to type 'BodyInit'.
Type 'MyClass' is not assignable to type 'ReadableStream'.
Property 'readable' is missing in type 'MyClass'.
Run Code Online (Sandbox Code Playgroud)
我的课:
class MyClass {
configId: string;
adapterType: string;
address: string;
constructor(configId: string, adapterType: string, address: string) { …Run Code Online (Sandbox Code Playgroud) 如何在nodejs/node-fetch POST请求中附加文件.我想调用导入文件的API(.xls或csv).如何使用Node-fetch/nodejs执行此操作.
我正在使用 i mgur api通过节点 js 应用程序上传图像。
我正在将图像转换为 base64 字符串并通过 Postman 发送它们效果很好。
我node-fetch用来进行api调用。
const fetch = require('node-fetch')
...
async uploadImage(base64image) {
try {
const url = 'https://api.imgur.com/3/image'
const res = await fetch(url,
{
method: 'POST',
body: { image: base64image },
headers: {
'content-type': 'application/json',
'Authorization': 'Client-ID [my-client-id]',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, Access-Control-Allow-Headers',
'Access-Control-Allow-Methods': 'POST',
}
}
)
console.log(res)
} catch(err) {
console.log(err)
}
}
Run Code Online (Sandbox Code Playgroud)
错误:从源“ http://localhost:3000 ”获取“ https://api.imgur.com/3/image ”的访问已被 CORS 策略阻止:请求标头字段Access-Control-Allow-Headers为预检响应中的Access-Control-Allow-Headers 不允许。 …
我最近开始使用原生的 fetch 功能(节点 17+)
我今天意识到它缺少一些功能node-fetch,例如agent
这是为什么?
有计划添加吗?
很遗憾,因为我需要添加node-fetch到我的项目中
看
在邮递员中,我可以成功地提出这个要求:
得到这个回应:
现在我想在node.js中的server.js文件中执行相同的请求:
const fetch = require('node-fetch')
const SEN_URL = "http://www.sentiment140.com/api/bulkClassifyJson" // URL of sentiment analysis
app.get('/api/sentimenttest', async (req, res) => {
try{
var sentiments = await fetch(SEN_URL, {method: "POST", body: {"data": [{"text": "I love you"}, {"text": "I hate you"}]}})
console.log(sentiments)
res.send(sentiments)
}catch(error){
console.log(error)
}
})
Run Code Online (Sandbox Code Playgroud)
这不起作用.这是我去localhost时在浏览器中显示的内容:5000/api/sentimenttest:
{"size":0,"timeout":0}
Run Code Online (Sandbox Code Playgroud)
这是控制台输出:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: true,
_transformState: [Object] }, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Jest 在 Typescript 中编写集成测试node-fetch,如下所示:
import fetch from 'node-fetch';
test('Hello', async () => {
await fetch("http://www.google.com");
});
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
Jest encountered an unexpected token
[...]
Details:
/home/xxx/node_modules/node-fetch/src/index.js:9
import http from 'node:http';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import fetch from 'node-fetch';
| ^
2 |
3 | test('Hello', async () => {
4 | await fetch("http://www.google.com");
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (temp.test.ts:1:1)
Run Code Online (Sandbox Code Playgroud)
我已经尝试过其他问题中给出的一些解决方案,但它们不起作用;我认为我的问题略有不同,因为一般来说并不妨碍我使用 ES6 风格的 important,但它特别不适用于node-fetch. 例如,我可以import …
node-fetch ×10
node.js ×9
javascript ×6
typescript ×3
jestjs ×2
cors ×1
discord.js ×1
fetch ×1
fetch-api ×1
file ×1
hypixel-api ×1
imgur ×1
post ×1