Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Am I Getting 502 Error After Adding Require In Express JS File?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Have you looked at the console for your server process? It’s probably spewing out errors.

  • You need a semicolon (;), not a colon (:) after require()
  • Then, you’d get "can’t resolve getJSON.js" since what using an absolute path in require would refer to a module in node_modules. Instead, if docapi.js and getJSON.js are in the same directory, you’ll want
    const getJSON = require('./getJSON.js');
    
  • Thirdly, the syntax in getJSON.js is 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading