Cannot configure Router in Express NodeJS - node.js

I have the next server file:
'use strict'
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const index = require('./routes/index');
const chat = require('./routes/chat');
app.use('/', index);
app.use('/chat', chat);
const port = process.env.API_PORT || 8989;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
and the next two routes index.js and chat.js in ./routes dir:
// ./routes/index.js
const express = require('express');
const router = express.Router();
router.route('/')
.get((req, res) => {
res.json('Hello on the Homepage!');
});
module.exports = router;
// ./routes/chat.js
const express = require('express');
const router = express.Router();
router.route('/chat')
.get((req, res) => {
res.json('Hello on the Chatpage!');
});
module.exports = router;
The first one index.js loads normaly by standart port localhost:8989/, but when I what to get the second route by localhost:8989/chat - I always receive error - Cannot GET /chat...
What is I'm doing wrong?

In server.js
const index = require('./routes/index');
const chat = require('./routes/chat');
app.use('/chat', chat); // when path is :/chat/bla/foo
app.use('/', index);
In ./routes/index.js
router.route('/')
.get((req, res) => {
res.json('Hello on the Homepage!');
});
In ./routes/chat.js
// It is already in `:/chat`. There we need to map rest part of URL.
router.route('/')
.get((req, res) => {
res.json('Hello on the Chatpage!');
});

// ./routes/chat.js
const express = require('express');
const router = express.Router();
router.route('/')
.get((req, res) => {
res.json('Hello on the Chatpage!');
});
module.exports = router;
you can use this

Related

Nodejs is not able to work after creating different routing files

I have an error while running my index.js file after separating the code into different files.
I'm running index.js in the terminal in the right folder as required.
This is my index.js file:
const express = require("express");
const app = express();
const Joi = require("joi");
const genres = require("./routes/genres");
const home = require("./routes/home");
app.use(express.json());
app.use("/api/genres", genres);
app.use("/api/home", home);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`you are listening to port ${port}`));
This is my genres file for routing:
const express = require('express');
const router = express.Router();
.
.
.My routing settings
.
.
module.exports = router;
This is the error that I get in vs code after running index.js via terminal:
Will be glad to get any assistance.
index.js
const genres = require("./routes/genres")(app);
const home = require("./routes/home")(app);
app.use("/api/genres", genres);
app.use("/api/home", home);
genre.js
const express = require('express');
const router = express.Router();
router
.get('/', async (req, res) => {
res.send('get data');
})
.post('/add', async (req, res) => {
res.send('get data');
})
module.exports = router;

How to access my IPFS node instance from my express router

I can't seem to work out the correct approach for running a IPFS node in my express app (/services/IPFS.js), while also being able to access it within my routes (/routes/uploads.js)
/services/IPFS.js
const IPFS = require("ipfs-core");
module.exports = startNode = async (req, res, next) => {
console.log("Starting IPFS node...");
return await IPFS.create();
};
index.js
const express = require("express");
const bodyParser = require("body-parser");
const apiRouter = require("./routes/api");
const cors = require("cors");
const app = express();
const port = 4000;
const startNode = require("./services/IPFS");
app.use(cors());
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use("/api/v1", apiRouter);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
startNode();
How do I pass my IPFS instance through to /routes/upload.js so I can use ipfs.add(file) in my /upload endpoint?
Any help appreciated.
Thanks
You could define the apiRouter as a factory function and pass the startNode function to it. In your router you can then call it:
// in your index.js
// ...
app.use("/api/v1", apiRouter(startNode));
// ...
// in your apiRouter.js
const express = require('express');
const router = express.Router();
module.exports = (startNodeFn) => {
router.post('/upload', async (req, res) => {
const result = await startNodeFn.call(startNodeFn, req, res);
// handle result and do upload ...
});
// rest of routes
// ...
return router;
}

Dynamic BaseUrl in ExpressJs

I'm trying to set the base URL for an Express app on startup.
I can hardcode the base URL and it works just fine:
app.use("/mybaseurl", routes);
However, if I try to use a variable instead which I can export on startup, it fails:
const baseUrl = "/mybaseurl";
app.use(baseUrl, routes);
The above doesn't work.
What am I missing?
test this code, work for me: http://localhost:3000/test
app.js:
const express = require('express');
const userRouter = require('./user');
const app = express();
app.use(express.json());
const baseUrl = '/test';
app.use(baseUrl, userRouter);
app.listen(3000, ()=> {
console.log('Server is up on port ', 3000)
});
user.js:
const express = require('express');
const router = new express.Router();
router.get('/', async (req, res) => {
res.status(200).send('hello');
});
module.exports = router;

How can I separate route files?

I have a route file in my project and it is called from my app with these lines:
var index = require('./routes/index');
app.use('/', index);
But I need to separate the route file, and I'm trying to do this:
var index = require('./routes/index');
var user = require('./routes/user');
app.use('/', index);
app.use('/user', user);
In route user.js I put the service that I need to access from the client. But it's not working. I don't know what is wrong, I am a beginner in Node.js.
The request returns:
GET /user/find 304 4.203 ms - -
And user.js file is:
var router = express.Router();
router.get('/user/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
*This request works well on index.js
You put user router under /user route, and in your user router you defined app.get('/user/find'), so the actual path would be /user/user/find, you need to remove the user prefix in router
var router = express.Router();
router.get('/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
A simple way to do this can be:
index.js
var express = require('express')
var app = express()
var route1 = require('./route1')
var route2 = require('./route2')
app.use('/', route1);
app.use('/hello', route2);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
route1.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route1');
})
module.exports = router
route2.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route2');
})
module.exports = router
Have you made sure to include a module.exports = router at the end of each of your route files?
Your route files should be set up thusly:
var router = require('express').Router();
router.get("/example", function (req, res) {
res.send("Hello");
});
module.exports = router;

Node.js/Express redirect all to angular 2 page

I am creating an Angular 2 app with Node.js and Express.
The problem I am having is that my routes file doesnt work with a wildcard. Everytime I visit the page with anything other then / (for example /test) it says the following: ReferenceError: path is not defined
My server.js:
const express = require('express');
const app = express();
const path = require('path');
const routes = require('./routes');
const data = require('./articles.json');
app.use(express.static(path.join(__dirname, '/dist')));
app.use('/', routes);
app.listen(8080, function () {
console.log('App started on port 8080');
});
My /routes/index.js:
const routes = require('express').Router();
routes.get('*', function (req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
module.exports = routes;
So what am I doing wrong here?
You need to require the path package in your index.js too
/routes/index.js
const path = require('path');
const routes = require('express').Router();
routes.get('*', function (req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
module.exports = routes;

Resources