簡體   English   中英

如何從 http 獲取 url 參數

[英]how to get the url parameters from http

我正在為 nodejs 中的小型 CMS 開發一個非常基本的“路由”系統,沒有 express 或任何框架。 我的目標是很少有依賴關系。 對於模板,我發現 jrender 在下面的示例路線“嘿”中工作正常:

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

var html = jsrender.renderFile('./templates/hey.html', {name: "Jim", age: "22"});


http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'}); // http header

    var url = req.url;
    if(url ==='/about'){
        console.log (req.url)
        res.write("hey"); //write a response
        res.end(); //end the response

    }else if(url ==='/contact'){
        res.write('<h1>contact us page<h1>'); //write a response
        res.end(); //end the response

    }else if(url ==='/hey'){
        res.write(html); //write a response
        res.end(); //end the response    

    }else{
        res.write('<h1>Hello World!<h1>'); //write a response
        res.end(); //end the response
    }

}).listen(3000, function(){
    console.log("Judge Dress live on port 3000"); //the server object listens on port 3000
}); 

我的問題是獲取頁面的參數,例如 /?pages=pagename 以具有動態路由。 有沒有辦法從 req.url 中提取這個參數?

您可以使用 node.js 內置的“查詢字符串”模塊。 從“ http://localhost:3000/about/?pages=me ”中獲取“我”

const querystring = require('querystring');     
console.log(querystring.parse(req.url)["/about/?pages"])

內置url模塊完全符合您的要求,如其文檔中所述:

> var url = require('url')
> url.parse('some.com/?url=hi&foo=bar', true)
Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?url=hi&foo=bar',
  query: { url: 'hi', foo: 'bar' },
  pathname: 'some.com/',
  path: 'some.com/?url=hi&foo=bar',
  href: 'some.com/?url=hi&foo=bar' }

查看query屬性? 請求參數的鍵/值對。

https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM