Home > Software engineering >  Why Am I Getting 502 Error After Adding Require In Express JS File?
Why Am I Getting 502 Error After Adding Require In Express JS File?

Time:02-13

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?

CodePudding user response:

502 is a Bad Gateway error.

Your reverse proxy server can't connect to the Node.js server because the Node.js server fails to start due to the syntax errors in your files.


First: getJSON.js.

A function declaration starts with the function keyword, but you omitted it.

The syntax you are using is for declaring a method, which is only allowed inside a class or object.


Second, you followed your call to require with a colon instead of a semi-colon.


You should have an error report when you tried to start the server (be it locally or on whatever service you are deploying the code to). You really should examine that before resorting to SO.

You should also make use of tools like ESLint which will pick up this kind of error and will integrate with common IDEs (such as the popular, and free, Visual Studio Code).


Once your fix your syntax errors, you need a relative path (e.g. starting with ./) to require a file in the same directory.

You also need to export the function for the assignment from require to do anything useful.

CodePudding user response:

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.
  • Related