To put my problem as simply as possible, I’m using Vercel for hosting my project. Vercel allows you to easily create your own REST server by basically creating an api
folder at your project root and then you can make requests to any files in that directory which will call serverless functions that perform specific functionality via simply calling the route and filename (so if I wanted to make a request to my user.js
file, I’d simply make a request to /api/user
).
I have several different folders and files in my api
folder that all work as expected when making AJAX calls to them. When I make a request to the index.js
file in my blog folder by simply making a request to /api/blog
, everything works fine, however, when trying to make get
request to /api/blog/someId
(someId
can be any string) I get the following error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:
C:UsersMeDocumentseatsleepcode.orgapiblog[id].js
require() of ES modules is not supported.
require() of C:UsersBrettDocumentseatsleepcode.orgapiblog[id].js from
C:UsersMeAppDataRoamingnpmnode_modulesvercelnode_modules@vercelnodedistlauncher.js
is an ES module file as it is a .js file whose nearest parent package.json contains "type":
"module" which defines all .js files in that package scope as ES modules.
Instead rename [id].js to end in .cjs, change the requiring code to use import(), or remove
"type": "module" from C:UsersBrettDocumentseatsleepcode.orgpackage.json.
I simply just want the someId
portion of the /api/blog/someId
url, which I was told you access by making a file with this naming syntax [randomParameter].js
and properly route to it (/api/blog/someParameter
).
Also, my package.json
has "type":"module"
defined in it, before anyone suggests the obvious.