Node Express dynamic route/path - javascript

How can I implement and get a dynamic route or path with Express package? The main problem is the path is an id pass by the client and had no control over it.
const express = require('express');
const dynamic_path= express();
dynamic_path.get('/user', (req, res) => {
});
exports.v1 = functions.runWith(runtimeOpts).https.onRequest(dynamic_path);
The above will result as https://my-app.net/v1/user and the client request will be https://my-app.net/v1/user/user_id. I need to allow dynamic path and I need to get the value of user_id as well for future usage.

Added :user_id to the route.
dynamic_path.get('/user/:user_id', (req, res) => {
const user_id = req.params.user_id;
});

Use the route:
https://my-app.net/v1/user/:user_id
Your code will be like this:
dynamic_path.get("/user/:user_id" , (req, res)=>{
let user_id = req.parmas.user_id
}

Related

Separating express queries from routes

I'm trying to make an express route that basically allows me to input an equity name as a query by putting ?symbol= on the URL. After the equity name, I want to add a new route.
const express = require("express")
const app = express()
app.get("/api/v1/equity/latest", (req, res) => {
res.send(req.query)
})
app.listen (3000, () => {
console.log("listening to port 3000")
})
when I give then GET the URL as localhost:3000/api/v1/equity?symbol=BBNI/latest/ and then look at the queries received, it received as symbol = BBNI/latest/
How do I separate the symbol query from the next /latest route?
It's a weird URL pattern, because if any dev sees this url:
/v1/equity?symbol=BBNI/latest/
It is implied that the symbol parameter is indeed BBNI/latest/ and not just BBNI
However, if you want to 'separate' these parts, you can just do:
const [symbol, latest] = req.query.symbol.split('/', 2);
But you probably should design a better URL structure.
I think it's not a good method.
Please try this.
const express = require("express")
const app = express()
app.get("/api/v1/equity/:symbol/latest", (req, res) => {
res.send(req.params.symbol)
})
app.listen (3000, () => {
console.log("listening to port 3000")
})

Is it possible a single API handles multiple requests in Node JS?

My goal is to create an API that handles multiple requests. By doing this, I need to pass a string as an argument to the url of API like this:
// index.js in client
fetch(`http://localhost:4000/routerName/${tableName}`).then()
// router.js
router.get(`/${tableName_from_client_page}`, (req, res) => { // Do Something })
A problem is, the browser can't connect to the targeted pages unless I create a whole new APIs for every matching tableNames.
I want my API handles multiple requests by receiving the tableName as its /url.
Are there some tricks to solve this problem?
This is how my whole router looks like:
// Router
const express = require('express'),
db = require('./db.js'),
router = express.Router();
router.get('/table', (req, res) => {
db.loadTable('SELECT * FROM someTable', res);
}) // Handles only one request on the name of url; /table
router.get(`/${tableName_from_client_page}`, (req, res) => {
db.loadTable(`SELECT * FROM ${tableName_from_client_page}`, res)
}) // Handles multiple requests, depending on its argument.
module.exports = router;
// Router
const express = require('express'),
db = require('./db.js'),
router = express.Router();
router.get('/table', (req, res) => {
db.loadTable('SELECT * FROM someTable', res);
}) // Handles only one request on the name of url; /table
router.get('/tables/:tableName', (req, res) => {
db.loadTable(`SELECT * FROM ${req.params.tableName}`, res)
}) // Handles multiple requests, depending on its argument.
module.exports = router;
// Router
const express = require('express'),
db = require('./db.js'),
router = express.Router();
This API will only handle one request "/table".
router.get('/table', (req, res) => {
db.loadTable('SELECT * FROM someTable', res);
})
To handle multiple requests checkout below code
but make sure to write this API last in the route file, If you write this API before the "/table" API then your "/table" request will also be handled by this API.
router.get('/:table_name', (req, res) => {
db.loadTable(`SELECT * FROM ${req.params.table_name}`, res)
})
module.exports = router;

Request parameter in Express router

I'm having some trouble accessing request parameters in express router.
My server.js file has this:
app.use('/user/:id/profile', require('./routes/profile');
And this is in my ./routes/profile.js file:
router.get('/', (req, res) => {
console.log(req.params.id);
}
But the console log prints undefined.
I'm new to express and feel like I'm missing something basic about how routing works.
Can someone please help me out?
Here is my full server.js:
const express = require('express');
const app = express();
app.use(express.json());
app.use('/user/:id/profile', require('./routes/profile'));
app.listen(5000, () => console.log('Listening'));
Here is my full profile.js:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
console.log(req.params.id);
res.status(200).send('In profile route');
});
module.exports = router;
URL parameters are not exposed to routers. You have a couple of options here:
Parse req.originalUrl to get the user id (not recommended). req.originalUrl isn't affected by the router's mount point and will remain as /user/112/profile or whatever url you visited.
Add some middleware to expose the id (recommended). Your new route statement will end up looking like this:
(Now you can use req.userId in your profile.js)
app.use('/user/:id/profile', function(req, res, next) {
req.userId = req.params.id;
next();
}, require('./routes/profile'));
Change the mount point from /user/:id/profile to /user, then edit your router to listen on /:id/profile (not recommended).

Is there a better way to structure Express (nodejs) application routes?

I have my app.js where I have the server created and this is where I define the main routes. I only added parts of my code.
const app = express();
const user = require("./routes/user/user");
app.use("/user", user);
In the ./routes/user/user.js I am able to define the routes like this
const express = require("express");
const router = express.Router();
router.get("/profile", (req, res) => {
/*some more code*/
});
router.post("/register", (req, res) => {
/*some more code*/
});
router.get("/timeline", (req, res) => {
/*some more code*/
})
module.exports = router;
Right now ./routes/user/user.js is not messy, but when we add more routes it can get pretty ugly.
My goal would be to have ./routes/user/combineUserRoutes.js where I could combine multiple requests without defining them there.
These request files would be structured something like this:
./routes/user/auth/register.js
./routes/user/profile/profile.js
./routes/user/timeline/index.js

request.body undefined after using express bodyParser

Edit: i fixed it by using:
app.configure(function(){
app.use(express.bodyParser());
});
Original post:
I'm trying to figure out how to handle a post with node and express and i'm completely stuck.
After some reading i noticed people saying i should use 'middleware' whatever that means and create a line app.use(express.bodyParser());. I assumed that after adding that i would have a req.body available in my post method. This isn't the case however. It console.log's into a undefined.
I think I don't know how to properly set this up, so here goes nothing:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, UserProvider = require('./userprovider').UserProvider,
qs = require('querystring');
var userProvider = new UserProvider('localhost', 27017);
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/new_game', function (req, res) {
res.sendfile(__dirname + '/new_game.html');
});
app.post('/new_game', function(req, res) {
var codeToUse = Math.random()*10000;
codeToUse = Math.round(codeToUse);
console.log(req.body);
});
app.use(express.bodyParser());
app.listen(3000);
Though you've said now your code works, but i won't suggest you to use bodyParser in the options of
app.configure()
What it does is that, if you use it as you have done, any file can be send into your system for all post requests. It's better if you use
express.json()
and
express.urlencoded()
in the options of
app.configure(),
and when you expect a file use bodyParser in the respective post route like this
app.post('/upload', express.bodyParser(), function(req, res){//do something with req.files})

Categories

Resources