• Register
0 votes
213 views

Problem :

I am just starting coding using the nodejs with express. So I simply did this in my file test.js which is into my folder routes :

const myexpress = require('express');
const myrouter = new myexpress.Router();
myrouter.get('/test', (req, res) => {
res.send(`I am the test`);
});
module.exports = myrouter;

Then, inside my server.js :

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

But in the browser, it tells me it Cannot get/test

I don't understand why this is happening to me. Please let me know how can I fix this?

by (3.9k points)  

1 Answer

0 votes

Solution :

A problem seems to be in how you are mounting your router. Looking at a router middleware API it seems you should be doing it as shown below.

test.js

const myexpress = require('express');
const myrouter = new myexpress.Router();
myrouter.get('/test', (req, res, next) => {
  res.send("I am the test");
  next();
});
module.exports = myrouter;

server.js

const myexpress = require('express');
const myapp = myexpress();
const mytest = require('./test'); 
app.use('/', mytest);
app.listen(3000);

OR

Below is the very simple fix that should resolve all your issues.

You need to Replace below code

const router = new express.Router();

With the following code.

const router = express.Router();

I hope you will be able to fix your error with the help of above given solutions.

by (36.1k points)  
...