P_Js
P_Js

Reputation: 623

nodejs Route.get() requires callback functions but got a [object String]

I'm starting coding using nodejs with express. So i did this in my file test.js which is into my folder routes :

const express = require('express');

const router = new express.Router();

router.get('/test', (req, res) => {
    res.send(`I'm a test`);
});

module.exports = router;

Then, in my server.js :

const test = require('./server/routes/test');
app.use('/test', test);

In my browser, it tells me Cannot get/test

I don't understand why. Need for help. Thanks

Upvotes: 0

Views: 6799

Answers (4)

Johnsons Gaming
Johnsons Gaming

Reputation: 101

Simple fix that should resolve your issue.

Replace

const router = new express.Router();

With

const router = express.Router();

Upvotes: 0

Skabbi
Skabbi

Reputation: 436

The problems seems to be how you are mounting the router. Looking the the router middleware API it seems you should be doing it like this.

test.js

const express = require('express');
const router = new express.Router();

router.get('/test', (req, res, next) => {
  res.send("I'm a test");
  next();
});

module.exports = router;

server.js

const express = require('express');
const app = express();
const test = require('./test'); 

app.use('/', test);

app.listen(3000);

Upvotes: 1

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37403

in order to access /test use router.get('/' and app.use('/test' because express will concatenate / and /test.

in your case you have to access /test/test so do this and enter /test in your borwser:

const express = require('express');

const router = new express.Router();

router.get('/', (req, res) => { res.send("I'm a test"); });

module.exports = router;

Then, in your server.js :

const test = require('./server/routes/test'); app.use('/test', test);

Upvotes: 0

Alan
Alan

Reputation: 379

Add "I'm a test" inside res.send(), I mean add " around that String.

Upvotes: 0

Related Questions