0

I am trying to seperate route from node.js server to folder routes. But it is not working.

When I run the server, console.log('hello from express') not printed . Also the res.send() is not executed.

routes/index.js

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

router.get('/api/hello', (req, res) => {
  console.log({ express: 'Hello From Express' });

  res.send({ express: 'Hello From Express' });
});

module.exports = router;

and server.js

var indexRoute=require('./routes/index.js');

app.use('/api/hello',indexRoute);

How can I solve the problem? Thanks in advance.

6
  • what isn't working? what's the exact problem you're having? Commented Dec 19, 2019 at 23:51
  • when i run the server , console.log('hello from express') not printed . Also the res.send() not executed Commented Dec 19, 2019 at 23:54
  • Ok, you are confused I think. current you would have to type /api/hello/api/hello for your code to do anything. Commented Dec 19, 2019 at 23:57
  • 1
    The problem is that you've duplicated the path in the server.js and in the router file. Remove the routers path write router.get('/', controller). This means that that controller path is routed from the parent path. In that case, the one defined in /api/hello. In you current code, access to: /api/hello/api/hello and should work. After my changes, you'll be able to access using /api/hello Commented Dec 19, 2019 at 23:57
  • Ok , this work.but is i hava another route .post('/api/world) what i hava to put router.get('',controller) Commented Dec 20, 2019 at 0:02

1 Answer 1

2

Change your code :

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

router.get('/', (req, res) => {
  console.log({ express: 'Hello From Express' });

  res.send({ express: 'Hello From Express' });
});

module.exports = router;

This code is about what to do when the use hits the route you specify in :

app.use('/api/hello',indexRoute);

So your route should only deal with after the /api/hello

Lets look at an example:

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

router.get('/hello', (req, res) => {
  res.send({ express: 'Hello From Express' });
});

router.get('/goodbye', (req, res) => {
  res.send({ express: 'Goodbye From Express' });
});

module.exports = router;

This route handler is now defined to handle [URL]/hello and [URL]/goodbye So lets hook it up on the site to the url [site]/greeting/:

app.use('/greeting', indexRoute);

Now on our site we have 2 routes [site]/greeting/hello and [site]/greeting/goodbye

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.