Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

379
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda