How to use ? as separator in webservice url - javascript

using nodejs / express, i'm trying to make a webservice using ? to separate url from parameters and then & as parameters separators.
when using this, it works
app.get("/tableref/:event/:queryObject", function(req, res) {})
or this one works also
app.get("/tableref:event&:queryObject", function(req, res) {})
but not this, I got 404 error:
app.get("/tableref?:event&:queryObject", function(req, res) {})
It seems that it is the ? that is the problem. Is there a way to authorize it? escape it?
I'd like to use express validator like this
Thanks

To get value from query string you don't need to specify those query string parameters in Express routes.
Your code should look like this
app.get("/tableref", function(req, res) {
res.json(req.query)
});
when you enter the URL localhost/tableref?hello&world you will get the response {"hello": "", "world": ""}
and if you want to pass data to query string variables, you can also enter the URL localhost/tableref?hello=world&foo=bar and you will get the response {"hello": "world", "foo": "bar"}

Related

Request to API based on URL/

I'm attempting to make a request to an API to get a users' avatar. This is the code I have, however it's returning a "player is not defined" error.
app.get(`/api/avatar/${player}`, function(req, res) {
res.redirect(`http://cdn.simulping.com/v1/users/${player}/avatar`);
});
Essentially, if the URL is /api/avatar/3925 it would send them to http://cdn.simulping.com/v1/users/3925/avatar.
Assuming you're using Express.JS for the routing, the correct way for doing that is:
app.get('/api/avatar/:id', function(req, res) {
res.redirect(`http://cdn.simulping.com/v1/users/${req.params.id}/avatar`);
})
Assuming you are using Express routing, then you would need to utilise route parameters.
The Express documentation provides:
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
In this case:
Route path: /api/avatar/:player
Request URL: http://localhost:3000/api/avatar/3925
req.params: { "player": "3925" }
The working code:
app.get('/api/avatar/:player', function(req, res) {
res.redirect(`http://cdn.simulping.com/v1/users/${req.params.player}/avatar`);
});
You can read more about it in the Route Parameters section of the Express Routing Guide.

Specific url and parameter in Node.js project

I have 2 qeustions :
1. I want my project's url to be like 127.0.0.1:8080/param=id and I couldnt do it, I tried:
app.get('/param=id', function(req, res) {
console.log(req.param("id"));
});
if I write '/param/:id' it works but I dont want the url to look like this
I want my program to send message according to the id a json message or string to the client
So my second question is how the client gets the response - I want the message to go throgh a script in the client's side?
I would suggest using req.query instead of req.params:
app.get('/', function(req, res) {
console.log(req.query.id);
// or you may still use req.param("id")
});
requesting it like
HTTP GET 127.0.0.1:8080/?id=my_id
query is a different way of sending data to the server, designed to send key-value pairs.
Though, if id is the only thing you want to send to the server, I would recommend to stick with params, e.g.:
app.get('/:id', function(req, res) {
console.log(req.params.id);
});
requesting it like
HTTP GET 127.0.0.1:8080/my_id

Express middleware not having an effect

I have the following code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.use(express.cookieParser());
var port = Number(process.env.PORT || 5000);
app.get('/test/:id', function(req, res) {
res.send(req.params);
});
app.listen(port);
console.log("Listening on port " + port);
When I hit http://localhost:5000/test/12345 in my browser, I see:
[]
But I'm expecting to see the populated req.params object with id: 12345. Any idea what I'm doing wrong?
Thanks.
Checked and saw that req.params is actually an associative array, which is almost similar to object but not quite. Not sure why express defined it as such. The only benefit it gets is the added length property for an array. And res.send will try to JSON.stringify your output, which in turn will see that it's an array and only take care of indexes which are numeric. Hence the empty [] as return value.
You can validate this by doing -
var myParams = {};
Object.keys(req.params).forEach(function(key){
myParams[key] = req.params[key];
});
res.send(myParams);
You can also see that JSON.stringify only cares about numeric index by defining your route as such -
app.get('/test/:0', function(req, res) {
res.send(req.params);
});
The response object will be named after your id. If you check it in your browser's traffic you can see a file called 12345. Though you can check that your server gets the id by logging it on the server side.
app.get('/test/:id', function(req, res) {
console.log(req.params);
res.send(req.params);
});
If you want to pass variables to a view you might want to use the res.render(...) function where you can pass in arguments.
To get the 123451 send the res.send(req.params.id);.
The reason why you are not getting anything using res.send(req.params) is because req.params is an instance of Array and default mechanism tries to covet an array into string which is giving you [].
What you could do to see all params is as follows:
app.get('/test/:id', function(req, res) {
res.send(require('util').inspect(req.params));
});
That will give you output like (using this URL http://localhost:5000/test/12345):
[ id: '12345' ]
That approach will also work with routes having more parameters e.g. the following code snippet and that request http://localhost:5000/test/name/234
app.get('/test/:name/:id', function(req, res) {
res.send(require('util').inspect(req.params));
});
will give you:
[ name: 'name', id: '234' ]
Alternatively, if you would like to get JSON formatted output of a JavaScript object, you can use res.json. But note that json will also generate [] if you perform res.json(req.params) as it will render req.params array in a standard way.
I hope that will help.
Note that as of 9th April 2014 (Express version 4.0.0) req.params is an object instead of an array so you should not have similar issues with v4.0.0 and your code should work as expected.
app.get('/test/:id', function(req, res) {
res.send(req.params);
});
The problem isn't your middleware. Neither bodyParser nor cookieParser provide the named url parameter parsing. That being said, your code looks correct to me. Are you absolutely certain you restarted your node server after making the code change?

How to iterate over body of POST request in Express.js?

I'm constructing a generic route handler for POST requests in NodeJS.
I need to iterate over the req.params of the POST request, without knowing beforehand what the parameters are.
I have tried the following without success:
console.log("checking param keys...")
Object.keys(req.param).forEach(function(key){
console.log(key +"is " + req.params(key) )
})
When I run this code, only the "Checking param keys..." gets printed.
Anybody knows how to do this?
I guess you're asking how to iterate form post from a url encoded POST request body, so it is bodyParser() middleware that did your trick.
req.params is an array that contains properties mapped by routing defined express app. see details from req.params, not the request body. Take the follow code for example:
var app = require("express")();
app.use(express.bodyParser());
app.post("/form/:name", function(req, res) {
console.log(req.params);
console.log(req.body);
console.log(req.query);
res.send("ok");
});
Then test it like this:
$ curl -X POST --data 'foo=bar' http://localhost:3000/form/form1?url=/abc
You will see the console output like this:
[ name: 'form1' ]
{ foo: 'bar' }
{ url: '/abc' }
So req.body is the right way to access request body, req.query is for read query string of all HTTP methods.

express.js: capture generic routes with numeric Id

I'm trying to define a generic handler for express.js routes
the idea is to get something like
get /api/xxx/yyy -> get all data
get /api/xxx/yyy/11-> get record 11
I need to capture xxx/yyy on one variable and 11 in another
this works fine:
app.get('/api/*', function(req, res, next) {
I'm not capturing anything, but I read it with the req.path property
But I can't seem to solve this:
app.get('/api/*/:id(\\d+)$', function(req, res, next) {
If I try with:
http://localhost:3000/api/clientes/2
this is what I get in req.params:
req.params = [ '2', id: 'clientes' ]
It seems like the path get binded to id, and the id is unbound to any variable.
moreover, if I try fetching this:
http://localhost:3000/api/clientes/nuevos/2
The route doesn't match
So, I'm looking for a regexp that allow me to catch several paths (xxx/yyy) and also the last one if it's a number (11)
I could solve it using a regular expression instead of a string:
app.get(/\/api\/(.*)\/(\d+)/, function(req, res, next) {
Now if I try with
http://localhost:3000/api/clientes/menores/71
I get
req.params = [ 'clientes/menores', '71' ]
But I'd like to know if there's some way to use the :id marker...

Categories

Resources