最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Validating URL Query string in Node.js - Stack Overflow

programmeradmin1浏览0评论

A correctly formed query string looks like:

/update?id=123&foo=50&bar20

I want to map this "safely" into an object, but I don't want to end up with undefined values. Is there a nice way of validating the query string?

Details: I want to turn this into an object with the url module. i.e.:

var url_parts = url.parse(request.url, true);

and then I can route based on url_parts.pathname. I want to access url_parts.query.id, url_parts.query.foo and url_parts.query.bar, but only if they all exist and only if no other parameters were supplied, so that I don't get silent undefined values appearing.

A correctly formed query string looks like:

http://baseurl.thing/update?id=123&foo=50&bar20

I want to map this "safely" into an object, but I don't want to end up with undefined values. Is there a nice way of validating the query string?

Details: I want to turn this into an object with the url module. i.e.:

var url_parts = url.parse(request.url, true);

and then I can route based on url_parts.pathname. I want to access url_parts.query.id, url_parts.query.foo and url_parts.query.bar, but only if they all exist and only if no other parameters were supplied, so that I don't get silent undefined values appearing.

Share Improve this question asked Jan 24, 2011 at 15:47 YXDYXD 32.5k15 gold badges78 silver badges116 bronze badges 2
  • 2 I don't get it. You have the query object already, so why not just do if (query.id && query.foo && query.bar) { ... }? – Brian Donovan Commented Jan 24, 2011 at 15:51
  • I wanted to check that no other parameters were supplied, ie that it conforms exactly. I guess I can just ignore other parameters if it's a pain. – YXD Commented Jan 24, 2011 at 16:43
Add a ment  | 

1 Answer 1

Reset to default 6

set up defaults, and then overwrite them with values from your url.

EXAMPLE

var defaults = {
    id : 0,
    foo : 'default value',
    bar : 'default.value'
};

var url_parts = url.parse(request.url, true);
var query = url_parts.query;
query.prototype = defaults; //does the inheritance of defaults thing
// now query has all values set, even if they didn't get passed in.

Hope that helps!

发布评论

评论列表(0)

  1. 暂无评论