Node JS - 如何使用URL查询字符串?

时间:2017-03-30 12:15:00

标签: javascript node.js

如何在NodeJS中使用URL查询字符串,如PHP' $ _GET [" query"]命令?

http://php.net/manual/en/reserved.variables.get.php

比如说你想扩展下面的代码,在/ page001部分使用?option = 1。

所以访问ServerURL / page001?option = 1会写" Page1:Option 001 Selected"。

ServerURL / page001?option = 2会写" Page1:Option 002 Selected"等

var http = require('http');
var fs = require("fs");
var location = require('location-href');

var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();

////////////////////

var http=require('http');
var url=require('url');

var server=http.createServer(function(req,res){
    var pathname=url.parse(req.url).pathname;
    switch(pathname){
        case '/page001':
            res.end('<div id="page001"><h2>Page 001</h2><div>Page 001 Content</div></div>');
            console.log("Page 001 Loaded");
        break;
        case '/page002':
            res.end('<div id="page002"><h2>Page 002</h2><div>Page 002 Content</div></div>');
            console.log("Page 002 Loaded");
        break;
        default:
            res.end('<div id="default"><h2>Default</h2><div>This is the default page</div></div>');
            console.log("Default page was loaded");
        break;
    }

}).listen(8080);

console.log("Running on Port 8080");

1 个答案:

答案 0 :(得分:2)

您必须解析您解析的URL的.search属性。有很多关于如何在此站点上解析查询字符串的示例。

var reqUrl = url.parse(req.url),
    search = reqUrl.search,
    pathname = reqUrl.pathname;