2

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.

2
  • could you add more information and what error you get Commented Jul 2, 2018 at 15:55
  • Also it is device and not dev Commented Jul 2, 2018 at 15:55

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Hello and thank you for your reply. I think I like your approach more.
downvote: POST has deferent semantic. Also consider caching / proxy handling.
@l00k Why? The answer contains methods to use in both POST and GET. Also why introduce things that OP doesn't require. You could always add to the answer if you have any points.
1

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}

2 Comments

hello, and thanks for the quick reply. I need to send a Json object in json format. this is meant to be a http request not a not url.
If you pass it this way you do get your object as a json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.