I am trying to require a js file in my express api but I am getting a 502 error whenever I do. The file getJSON.js is in the same directory as my express js file but for some reason I am having trouble accessing it:
docapi.js:
const http = require('http');
const getJSON = require('getJSON.js'):
const hostname = 'localhost';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Here is the file I am trying to require:
getJSON.js:
test() {
console.log("Hello again.")
}
Sorry for such an easy question, but I haven’t found an explanation anywhere else. Can anyone tell me what I am doing wrong, please?
>Solution :
Have you looked at the console for your server process? It’s probably spewing out errors.
- You need a semicolon (
;), not a colon (:) afterrequire() - Then, you’d get "can’t resolve
getJSON.js" since what using an absolute path inrequirewould refer to a module innode_modules. Instead, ifdocapi.jsandgetJSON.jsare in the same directory, you’ll wantconst getJSON = require('./getJSON.js'); - Thirdly, the syntax in
getJSON.jsis invalid: You’ll want e.g.function test() { console.log("Hello again.") } - And to be able to call that function from the other file, you’ll need to export it:
module.exports = function test() { console.log("Hello again.") } - After which you could do
const getJSON = require('./getJSON.js'); getJSON();in the other file.