简体   繁体   中英

Extra quotes in req.query object

I have a problem with extra quotes in req.query object. I'm using Angular.JS(1.5.8) with NodeJS(6.2.0). So what i mean: On client side I have simple REST api

.factory('Users', function ($resource) {
   var Users = $resource("api/users/" + ":_id", { _id: "@_id" }, {update: {method: 'PUT'}, query:{ method: "GET", isArray: false }});
   return Users;
 })

And use it like this

return Users.query({a: 'some text', b: 10}}).$promise.then(function(results){
            return results.users;
        });

And all works fine, on server I'm get as results console.log('Query parsing - ', req.query); - Query - { a: 'some text', b: '10' } But when I'm trying to send nested object: Users.query({a: 'some text', b: {first: 10, second: 20}}) On server I have results with extra quotes and object not valid: Query - { a: 'some text', b: '{"first":10,"second":20}' } . As result I cannot use it for mongoose queries. When I waited for {$text:{"$search":"admin"}} I'm recived {$text:'{"$search":"admin"}'} . Can someone faced this problem before. Thanks for the help

JSON/Object to QueryString and back conversion has many many issues. Nesting, Arrays, "null", boolean values etc. You just encountered one.

Simplest solution is to JSON.stringify() objects as query string value:

url = 'www.example.com' + '/resource' + '?json=' + JSON.stringify(dataObject);

Browsers will automatically URL encode the JSON string. On other clients you may have to do it manually.

You can parse it back on server. For example this expressjs middleware:

app.use(function(req, res, next){
   if(req.query.json){
      try {
        req.query.json = JSON.parse(req.query.json);
        next();
      }catch(err){
        next(err);
      }
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM