user7002255
user7002255

Reputation:

How to get JSON data from url in Node.js with Express

I am trying to get the a Json object from a url using Express:

this is my code:

app.get('/device/:id', (req, res, next) => {
     console.log('device: ' + req.params.id + ' Request received');
     let parsedContent = JSON.parse(req.query);
     //res.status(201).send('success');
 });

this my url:

http://localhost:4001/device/1?{"type":"fridge","pcb"=2.4}

I get an error on the parsing line.

Here is the error as requested:

SyntaxError: Unexpected token o in JSON at position 1
  at JSON.parse (<anonymous>)

I have also tried this:

app.get('/device/:id', (req, res, next) => {
    let query = url.parse(req.url).query;
    if( query ) {
        let parsedContent = JSON.parse(decodeURIComponent(query));
    }
});

With this url:

http://localhost:4001/device/1??type=fridge&pcb=2.4

Still the same issue.

Upvotes: 2

Views: 9895

Answers (2)

MjZac
MjZac

Reputation: 3536

If you want to send json data in request, it is better to make use of POST request. Then the server should accept post data.

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
}));

...

app.post('/device/:id', (req, res, next) => {
   console.log('device: ' + req.params.id + ' Request received');
   let parsedContent = JSON.parse(req.query);
   let payload = req.body.payload; // your json data
   //res.status(201).send('success');
});

if you insist on using GET request, you need to urlencode the query parameters before sending it to the server.

http://localhost:4001/device/1?payload=%7B%22type%22%3A%22fridge%22%2C%22pcb%22%3D2.4%7D

In your server code, you can access it as let payload = JSON.parse(req.query.payload)

Upvotes: 2

pr0p
pr0p

Reputation: 2358

Your url should be :

http://localhost:4001/device/1?type=fridge&pcb=2.4

You can't write a query as you did in your url. It has to follow the format.

? depicts the start of the query. Then you put the key value pair as key=value and if you have many of them then use single &

So ?key1=val1&key2=val2&key3=val3 ....

Your req.query will be :

{"type":"fridge","pcb"=2.4}

Upvotes: 1

Related Questions