Dynamic BaseUrl in ExpressJs - node.js

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;

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;
}

Cannot configure Router in Express NodeJS

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

NODE Cannot GET routes function

I have created a folder testint
My testint/app.js having following code
const express = require('express'); const path = require('path');
const bodyParser = require('body-parser'); const cors = require('cors');
const passport = require('passport'); const mongoose = require('mongoose');
const app = express(); const port = 7000; app.use(cors());
app.use(bodyParser.json());
app.use('/users', users); //Not working
app.get('/',(req,res) => {
res.send("Invalid Endpoint");
});
app.listen(port, () =>{
console.log('Server started on port '+ port);
});
testint/routes/users.js contains :
const express = require('express'); const router = express.Router();
res.send('Authenticate');
router.get('/register',(req, res, next) => {
res.send('REGISTER');
});
module.exports = router;
If I run http://localhost:7000/users/register
Am getting :
Cannot GET /users/register
I dint know where am wrong and am new to node any help will be appreciated.
I got solution. I didn't include
const users = require('./routes/users');
in app.js
and res.send('Authenticate'); in users.js is not required for instance.

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