Nathan_Dev
Nathan_Dev

Reputation: 11

NodeJs + Express - Cannot GET /

I run it in repl.it and I get the error Cannot GET /

Sometimes it works and sometimes it doesn't work on the specific port which is 45799 but now it's not working again.

Here's the code:

app.set('view engine', 'ejs');
app.use('/public', express.static('public'));
app.use(bodyParser.json());

app.get('/', (req, res) => {
app.render('index', {
    bot: bot
}, (err, html) => {
    res.send(html)
    if (err) console.log(err)
})
});

app.get('/commands', (req, res) => {
app.render('commands', {
    bot: bot
}, (err, html) => {
    res.send(html)
    if (err) console.log(err)
})
});

app.get('/premium', (req, res) => {
app.render('premium', {
    bot: bot
}, (err, html) => {
    res.send(html)
    if (err) console.log(err)
})
});

app.get('/staff', (req, res) => {
app.render('staff', {
    bot: bot
}, (err, html) => {
    res.send(html)
    if (err) console.log(err)
})
})

let listener = app.listen(45799, (err) => {
     console.log('Your app is currently listening on port: ' + listener.address().port);
     if (err) console.log(err)
});```

Upvotes: 1

Views: 1249

Answers (2)

hyundeock
hyundeock

Reputation: 505

Express is a function that returns app.

And the app object has a method corresponding to http.

For example, put, get, post, etc.

This method takes a url as the first argument and a callback function as the second argument.

This callback function has three arguments: "req" for incoming request, "res" for response processing, and "next" to pass to the next middleware.

("req", "res" and "next" name is up to you.)

If you want to render ejs file, then use "res.render" not "app.render".

Upvotes: 0

Prathamesh More
Prathamesh More

Reputation: 1489

You rendering the wrong way. You have to use the res object instead of app

const express = require('express');
const bodyParser = require('body-parser')
const app = express();

app.set('view engine', 'ejs');
app.use('/public', express.static('public'));
app.use(bodyParser.json());

const bot = { "data": "1" }
app.get('/', (req, res) => {
  res.render('index', { bot: bot });
});


app.listen(3000, () => {
  console.log('server started');
});

Upvotes: 1

Related Questions