web开发概述(06):参数传递和获取—get参数处理
方法
/*
get参数处理
*/
const url = require('url');
let str = 'https://www.baidu.com/s?ie=UTF-8&wd=nodejs';
let ret = url.parse(str);
console.log("ret",ret);
/*
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com',
hash: null,
search: '?ie=UTF-8&wd=nodejs',
query: 'ie=UTF-8&wd=nodejs',
pathname: '/s',
path: '/s?ie=UTF-8&wd=nodejs',
href: 'https://www.baidu.com/s?ie=UTF-8&wd=nodejs'
}
*/
//true query返回为对象
let ret2 = url.parse(str,true);
console.log("ret2",ret2);
/*
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com',
hash: null,
search: '?ie=UTF-8&wd=nodejs',
query: [Object: null prototype] { ie: 'UTF-8', wd: 'nodejs' },
pathname: '/s',
path: '/s?ie=UTF-8&wd=nodejs',
href: 'https://www.baidu.com/s?ie=UTF-8&wd=nodejs'
}
Process finished with exit code 0
*/
let obj = {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com',
hash: null,
search: '?ie=UTF-8&wd=nodejs',
query: { ie: 'UTF-8', wd: 'nodejs' },
pathname: '/s',
path: '/s?ie=UTF-8&wd=nodejs',
href: 'https://www.baidu.com/s?ie=UTF-8&wd=nodejs'
};
let ret3 = url.format(obj);
console.log("ret3",ret3);
测试
/*
测试get
*/
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
let obj = url.parse(req.url,true);
res.end("username:"+obj.query.username + " password:" + obj.query.password);
}).listen(3000,()=>{
console.log("启动");
});
/*
http://localhost:3000/?username=dede&password=123456
username:dede password:123456
*/

浙公网安备 33010602011771号