node学习(1) -- HTTP模块/URL模块

(一) 运行服务

首先我们先来学习一种最简单的用命令行跑node代码的方式:
到当前node代码所处文件下,假设我们的代码在study.js中,则运行node study.js即可;

这里写图片描述

可是上述方法有一个特别不好的地方, 就是每一次我们修改之后都要重新执行一下。

接下来就来介绍一个自启动工具supervisor,有了他就能实时的监听页面变化
使用也很简单:全局安装该工具

npm install -g supervisor

然后将我们之前执行的 node 替换成 supervisor 就可以了

(二) http模块

// 引用http模块
var http = require('http');

// 创建一个服务
var server = http.createServer(function(req,res){
    // req 表示请求的内容 ; res 表示响应的内容
    res.writeHead(200, {"Content-Type": "text/html;charset=UTF8"}); // 设置响应头
    res.write('响应的内容');
    res.end(); // 此方法使web服务器停止处理脚本并返回当前结果
});

server.listen(3000); // 监听3000端口

这里写图片描述

(三) url模块

url模块主要是用来处理用户请求的url地址,即req.url

我们主要了解下url的几个方法:

  1. url.parse() 解析url

(1) 不带查询字符串的情况

Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com',
  port: null,
  hostname: 'www.baidu.com',
  hash: null,
  search: null,
  query: null,
  pathname: '/',
  path: '/',
  href: 'http://www.baidu.com/' }

(2)带查询字符串的情况 , 可以在search / query处拿到

Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com',
  port: null,
  hostname: 'www.baidu.com',
  hash: null,
  search: '?username=test&password=123',
  query: 'username=test&password=123',
  pathname: '/',
  path: '/?username=test&password=123',
  href: 'http://www.baidu.com/?username=test&password=123' }

(3)第二个参数设置为true, 默认为false,
将query中的查询字符串转化成对象格式

Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com',
  port: null,
  hostname: 'www.baidu.com',
  hash: null,
  search: '?username=test&password=123',
  query: { username: 'test', password: '123' },
  pathname: '/',
  path: '/?username=test&password=123',
  href: 'http://www.baidu.com/?username=test&password=123' }

(4) 第三个参数设置为true , 默认为false

// 这种是默认情况下应该显示的, 此时第三个参数就是默认的false 
// 这种情况下//后面的内容都会被归属到pathname中
Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: null,
  query: null,
  pathname: '//foo/test',
  path: '//foo/test',
  href: '//foo/test' }

// 下面这种情况就是我们手动的将第三个参数设置为true
// 这种情况下 会将 //到下一个/之间的内容作为host,/后面的内容作为pathname
Url {
  protocol: null,
  slashes: true,
  auth: null,
  host: 'foo',
  port: null,
  hostname: 'foo',
  hash: null,
  search: '',
  query: {},
  pathname: '/test',
  path: '/test',
  href: '//foo/test' }
  1. url.format url.parse的逆向操作
var urlParse = url.parse('http://www.baidu.com');
var urlformat = url.format(urlParse); // http://www.baidu.com
  1. url.resolve(from, to) 添加或者替换地址
    from : 解析时相对的基本url
    to: 要解析的超链接url
url.resolve('/one/two/three', 'four') // '/one/two/four'
url.resolve('http://www.baidu.com/', 'four') // 'http://www.baidu.com/four'
url.resolve('http://www.baidu.com/three', 'four') // 'http://www.baidu.com/four'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值