nodejs
nodejs
nodejs 介绍
nodejs运行在服务器端的js; 非阻塞I/O; 基于谷歌的V8引擎
nodejs 模块
- 内置模块
- 第三方模块
- 自定义模块
nodejs 搭建服务器
需要借助 http 模块 搭建服务器
const http = require('http');
// req: 客户端向服务器请求
// res: 服务器向客户端响应
http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, {
"Content-type":"text/plain; charset=utf-8"})
// 返回数据
res.write(data);
// 终止响应 也可以返回数据
res.end()
// 服务正确开启,需要监听3000 端口
}).listen(3000, () => {
console.log('server runnning ....')
})
nodejs 的 url 模块
url 模块可以解析 url 地址 ; 通过 url.parse()
方法 解析地址 转化为一个对象
const url = require('url');
const path = 'https:://baike.baidu.com/xiaoshuo?kerywods=hello#3';
let res = url.parse(path);
/*
Url {
protocol: 'https:', // 协议
slashes: null,
auth: null,
host: null, // 主机
port: null, // 端口号
hostname: null, // 主机名
hash: '#3', // 哈希 url地址中 #后的内容
search: '?kerywods=hello', // 搜索 url 地址中 ? 开始往后的内容, 不包含hash
query: 'kerywods=hello', // 查询 url 地址中 ? 后边的内容 传递的数据
pathname: '://baike.baidu.com/xiaoshuo', // 访问的地址(请求资源的路径)
path: '://baike.baidu.com/xiaoshuo?kerywods=hello', // 路径
href: 'https:://baike.baidu.com/xiaoshuo?kerywods=hello#3' // 详细的url地址
}
*/
如果需要获取url地址中传递的数据, 需要传递第二个参数 url.parse(url, true)
对url 中的 query 字段解析为对象
let res = url.parse(path, true);
Url {
protocol: 'https:',
slashes: