I'm building a REST api server in Node js. Let's say I have an Api - http://localhost:3000/api/employee/:employeeId. And I want to fetch the employeeId parameter without using any framework such as Express js. If possible what would be a better approach ?
**If you Need the Employee Id from Url So You can use this - **
const express = require('express');
const router = express.Router();
router.get('http://localhost:3000/api/employee/:employeeId',getUserById);
getUserById(req, res) {
console.log('---EmployeeId ----',req.params.employeeId);
}
Here's a vanilla js function to get the url segments
function UrlSegments() {
// Change this to the correct url if its not
// the url that you want to process
// You can also do window.location.pathname to process
// the current path.
let urlSegments: string[] = /api/employee/:employeeId
// Remove the empty string before the first '/'
if (urlSegments.shift() === "")
urlSegments.slice(1, -1);
// Remove the empty string after the last '/'
if (urlSegments.slice(-1)[0] === "")
urlSegments.splice(-1, 1);
return urlSegments;
}
string employeeId = UrlSegments()[2];
Related
app.js
var bodyParser = require('koa-bodyparser');
app.use(bodyParser());
app.use(route.get('/objects/', objects.all));
objects.js
module.exports.all = function * all(next) {
this.body = yield objects.find({});
};
This works fine for get all objects. But I wanna get by query param, something like this localhost:3000/objects?city=Toronto How to use "city=Toronto" in my objects.js?
You can use this.query to access all your query parameters.
For example, if the request came at the url /objects?city=Toronto&color=green you would get the following:
function * routeHandler (next) {
console.log(this.query.city) // 'Toronto'
console.log(this.query.color) // 'green'
}
If you want access to the entire querystring, you can use this.querystring instead. You can read more about it in the docs.
Edit: With Koa v2, you would use ctx.query instead of this.query.
Node.js + Express project. Working on pagination I want to create the pagination links. Imagine the following URL:
http://server.com/products?page=1&color=red&size=big
I am here:
exports.products = function(req, res) {
}
I could use req.query.page and req.url and compose new URL for next and previous pages using regex and string functions for increasing/decreasing page parameter, but the question is:
Is there a cleaner method?
Some bodyparser feature?
Simple example (without input validation, but that's left as an exercise):
var toQS = require('querystring').stringify;
exports.products = function(req, res) {
...
req.query.page = Number(req.query.page) + 1;
var newUrl = req.path + '?' + toQS(req.query);
...
};
I was wondering how you would use node.js to parse a string parameter from a request url akin to express.
I know this is possible with express, but I would like to know how it can be done with node.js without express.
Express example:
var app = require('express')();
app.get('sample/request/url/:id', function(req, res) {
var parameter = req.params.id;
});
If your are using connect (or just http module) you can use RegExp:
With http:
var http = require('http');
http.createServer(function (req, res) { // Note there's no next here
var match = req.url.match(/^sample\/request\/url\/(.+)$/);
var id = match ? match[1] : null;
}).listen(3000);
...
With connect:
var connect = require('connect');
connect.createServer(funcion(req, res, next) {
var match = req.url.match(/^sample\/request\/url\/(.+)$/);
var id = match ? match[1] : null;
}).listen(3000);
...
This is the simple case. If you want to have your own routing middleware you should start with an array of RegExps (that can be generated dinamically from a String that you add) and loop through them until you find a match.
Each route element should have its RegExp and also its parameters, so that once you find a match you can extract and append the parameters to the req object with an appropriate name that you choose.
EDIT:
As robertklep pointed out in his comment, you can check paramify. Its code is very clear and does some of the things I said in the last part of the answer. For example, you can see it has a function regify to dinamically contruct the RegExps and a loop to extract the parameters of a match:
var params = []
for (var i = 1; i < matches.length; i++) {
var key = reg.keys[i - 1]
if (key) {
params[key.name] = matches[i]
} else {
params.push(matches[i])
}
}
You can get the url property from req and parse as you want:
var server = require('http').createServer(function (req, res) {
console.log(req.url);
// would log "/sample/request/url/123"
});
The parse part can be done using RegEx.
I have the following code, and node.js can't resolve the url:
const request = require('request')
const teamURL = `/users/${user._id}/teams`;
const req = request({
url: teamURL,
json: true
},
function(error, response, body) {
if (!error && response.statusCode == '200') {
res.render('userHome.html', {
user: user,
teams: body
});
}
else {
console.error(error);
next(error);
}
});
is there a good way to use relative paths/urls with the request library on a server-side node.js Express app?
Giving just a relative url only works if it is clear from context what the root part of the url should be. For instance, if you are on stackoverflow.com and find a link /questions, it's clear from context the full url should be stackoverflow.com/questions.
The request library doesn't have this kind of context information available, so it needs the full url from you to do be able to make the request. You can build the full url yourself of course, for instance by using url.resolve():
var url = require('url');
var fullUrl = url.resolve('http://somesite.com', '/users/15/teams');
console.log(fullUrl); //=> 'http://somesite.com/users/15/teams');
But of course this will still require you to know the root part of the url.
Jasper 's answer is correct -- the request module needs full URL. if you are in a situation where you have a single page application, with lots of requests to an API with the same base URL, you can save a lot of typing by creating a module like this:
var url = require('url');
var requestParser = (function() {
var href = document.location.href;
var urlObj = url.parse(href, true);
return {
href,
urlObj,
getQueryStringValue: (key) => {
let value = ((urlObj && urlObj.query) && urlObj.query[key]) || null;
return value;
},
uriMinusPath: urlObj.protocol + '//' + urlObj.hostname
};
})();
then, to grab the base URL anytime you need it: requestParser.uriMinusPath
and grab the value of an arbitrary query parameter: RequestParser.getQueryStringValue('partner_key');
I'm using express 3.0 and when I'm trying to resolve some queries I want to test if there's other component on the db that match these id's. Any way, this is the code I'm not getting to work:
function(req, res) {
var Parking = mongoose.model('Parking');
var parkingId = req.params.id;
var userId = req.user['_id'];
Parking
.findOne({'_id': parkingId}, function(err, parking) {
var parkingUserId = parking.userId;
if (userId == parkingUserId) {
...
} else {
...
}
req.params.id is inside url and req.user['_id'] comes from a middleware.
Although I'm calling this url with the same id on both fields.... it keeps getting false...
Why I'm doing wrong? thanks!
You need to convert parkingUserId from a bson ObjectId object to a string:
if (userId.toString() == parkingUserId.toString())