7

I'm new to Node.js and Express, I've been working on a RESTful API project, and I'm trying to send a GET request with multiple parameters in the URL:

Here is my route:

/centers/:longitude/:latitude

and here is how I tried to call it:

/centers?logitude=23.08&latitude=12.12

and I also tried

/centers/23.08/12.12

It ends up going to this route:

/centers/

So is my way of writing the endpoint wrong? or the way I'm requesting it?

Shawerma
  • 171
  • 1
  • 4
  • 12
  • Post your code of how you are calling and how you are receiving. – node_saini Dec 05 '16 at 05:59
  • 1
    Possible duplicate of [Node.js : Express app.get with multiple query parameters](http://stackoverflow.com/questions/19020012/node-js-express-app-get-with-multiple-query-parameters) – WitVault Dec 05 '16 at 06:01

3 Answers3

13

You are not correctly understanding how route definitions work in Express.

A route definition like this:

/centers/:longitude/:latitude

means that it is expecting a URL like this:

/centers/23.08/12.12

When you form a URL like this:

/centers?longitude=23.08&latitude=12.12

You are using query parameters (param=value pairs after the ?). To access those, see this question/answers: How to access the GET parameters after "?" in Express?

For that, you could create a route for "/centers" and then you would access req.query.longitude and req.query.latitude to access those particular query parameters.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
6

try like this

var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
app.get('/centers/:log/:lat',function(req,res)
       {
res.json({ log: req.params.log,
          lat: req.params.lat });

});
app.listen(port);
console.log('Server started! At http://localhost:' + port);

now try url like this http://localhost:8080/centers/55/55

enter image description here

Adiii
  • 54,482
  • 7
  • 145
  • 148
1

It`s easier to define url parameters in router .

Example url : http://www.example.com/api/users/3&0

in routes.js

router.get('/api/users/:id&:pending', function (req, res) {
  console.log(req.params.id);
  console.log(req.params.pending);
});
User123456
  • 2,492
  • 3
  • 30
  • 44