歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> node.js 接收get請求

node.js 接收get請求

日期:2017/3/1 10:33:52   编辑:Linux編程

Get 請求的相關方法一定在http.ServerRequest下,ServerRequest有data、end、close3個事件,method、url、headers、trailers、httpVersion、connection6個屬性,setEncoding、pause、resume3個方法。

url屬性下有一段說明描述了怎麼解析get請求:

request.url#

Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:

GET /status?name=ryan HTTP/1.1\r\n Accept: text/plain\r\n \r\n

Then request.url will be:

'/status?name=ryan'

If you would like to parse the URL into its parts, you can use require('url').parse(request.url). Example:

node> require('url').parse('/status?name=ryan') { href: '/status?name=ryan', search: '?name=ryan', query: 'name=ryan', pathname: '/status' }

If you would like to extract the params from the query string, you can use therequire('querystring').parse function, or pass true as the second argument to require('url').parse. Example:

node> require('url').parse('/status?name=ryan', true) { href: '/status?name=ryan', search: '?name=ryan', query: { name: 'ryan' }, pathname: '/status' }
說明中提到了require('url')和require('querystring') 可以分別查看API的URLQuery Strings小節

按照說明試一下吧(node> 表示 在命令行裡敲代碼)


那就結合 hello world 寫一個動態的hello world

[javascript]
  1. var http = require('http');
  2. var server = http.createServer();
  3. server.on('request',function (req, res){
  4. res.writeHead(200, {'Content-Type': 'text/plain'});
  5. var name = require('url').parse(req.url,true).query.name
  6. res.end('Hello World ' + name);
  7. });
  8. server.listen(1337, "127.0.0.1");
  9. console.log('Server running at http://127.0.0.1:1337/');
將以上代碼保存到 example3.js文件中,在cmd中敲入node example3.js

在浏覽器地址欄中敲入 http://127.0.0.1:1337/hello?name=myname


挺簡單的,下一節講復雜的post http://www.linuxidc.com/Linux/2012-02/53535.htm

Copyright © Linux教程網 All Rights Reserved