Creation of local server with express

Asked

Viewed 58 times

1

I installed the framework express in my root folder with all projects on Node, so it was easy to import the modules in all projects. But when I try to start a local server, with the following scope:

const reference = require("../node_modules/express");
const app = express();

app.listen(8081);

I always get the following message when trying to run the server through the terminal:

C:\Users\Usuário\Desktop\Node\serverExpress>node index.js
C:\Users\Usuário\Desktop\Node\serverExpress\index.js:9
const app = express();
            ^

ReferenceError: express is not defined
    at Object.<anonymous> (C:\Users\Usuário\Desktop\Node\serverExpress\index.js:9:13)
    at Module._compile (internal/modules/cjs/loader.js:1157:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load (internal/modules/cjs/loader.js:900:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47

As far as I know, the express function on line two comes along with the module import. What may be wrong?

  • 1

    which association between app and express() I’m not seeing, vc is assigning to app a value that it does not find.

  • 1

    const express = require('express');&#xA;const app = express();

2 answers

3


This is wrong:

As far as I know, the express function on line two comes along with the module import.

For something to be available in a file it needs to be explicitly imported.

That said, you matter the express in the constant reference but never makes use of it. The correct, as shown in Introducing of documentation, would be:

const express = require('express');
const app = express();

app.listen(8081);
  • 1

    You are correct Giovane, I was treating the express parameter as a function, when in fact I should reference the variable I declare on the top line.

2

To start a server using the express framework we need: define the port

const porta = 3003

import the express

const express = require('express')

assign to the app or other constant of your preference the express

const app = express()

now we can look at my-route in the browser that is using the verb get in this case.

app.get('/minha-rota', (req, res, next) => {
   res.send('alguma coisa')
})

don’t forget to listen at the door

app.listen(porta, () => {
console.log(`Servidor está executando na porta ${porta}.`)
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.