I'm making a website and I'm struggling with Require.js.
I want to require node-fetch
package:
const fetch = require('node-fetch');
// Getting avatar of random discord user
const token = process.env.TOKEN;
async function fetchit() {
const response = await fetch(`https://discord.com/api/v9/users/410902667318001684`, {
headers: {
Authorization: `Bot ${token}`
}
})
if (!response.ok) throw new Error(`Error status code: ${response.status}`)
else{
let obj = await response.json()
console.log(obj.avatar)
}
}
fetchit()
and I get this error:
Error: Module name "node-fetch" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
I tried using const fetch = require(['node-fetch'])
, but I got another error:
Error: Script error for "node-fetch"
https://requirejs.org/docs/errors.html#scripterror
This is my HTML script tag: <script data-main="script.js" src="require.js">
How can I fix this and get it working?
I use [email protected]
CodePudding user response:
You can't load node-fetch
using Require.JS.
Require.js is a module loader for AMD modules.
node-fetch
is a Common.JS module (which also depends on APIs provided by Node.js which aren't available in browsers).
AMD and Common.JS modules are very different module formats. Their loaders aren't compatible even if they do both use a function named require
(they use different functions named require
).
(As of version 3, node-fetch
has been converted to an ECMAScript module but still depends on Node.js and is still not compatible with Require.JS).
Use the browser-native Fetch API instead. node-fetch
is a library designed to be compatible with it so you can use the same API in browsers and Node.js.