前言:
我们用nodejs启用服务时经常会用到url模块来解析我们传来的路径,这里来说一说这个解析方法。
在我们js中可以直接用location.pathname来获取我们的url后缀:
例如:
localhost:8080/car/carIndex?a=2&b=2 然后用了location.pathname以后,得到/car/carIndex
但是,我们在node中是没有location的,所以我们serve服务启用后,用req.url来获取到路径,然后用url.parse(req.url).pathname 来得到我们想要的url后缀
const url = require('url');
//var a = url.parse('http://example.com:8080/one?a=index&t=article&m=default');
//a 输出结果:
//{
//protocol : 'http' ,
//auth : null ,
//host : 'example.com:8080' ,
//port : '8080' ,
//hostname : 'example.com' ,
//hash : null ,
//search : '?a=index&t=article&m=default',
//query : 'a=index&t=article&m=default',
//pathname : '/one',
//path : '/one?a=index&t=article&m=default',
//href : 'http://example.com:8080/one?a=index&t=article&m=default'
//}