node服务器端

创建web服务器

const http = require("http");
//创建web服务器,app就是网站服务器对象
const app = http.createServer();
//当客户端有请求来的时候
app.on("request", (req, res) => {
  res.end("<h1>hello world</h1>");
  // res.end("<h2>你好世界</h2>");
});
//监听端口
app.listen(3000);
console.log("服务器已启动,监听3000端口");

HTTP协议

请求报文

req.url          //获取请求地址
req.headers     //获取请求报文
req.method     //获取请求方法
app.on("request", (req, res) => {
  console.log(req.method)
  console.log(req.headers['accept'])		//获取具体键的内容
  if (req.url == "/index" || req.url == "/") {
    res.end("welcome to indexPage");
  } else if (req.url == "/list") {
    res.end("welcome to listPage");
  } else {
    res.end("404 Not Found");
  }
});

响应报文

  1. HTTP状态码
  • 200 请求成功
  • 404 请求的资源没有被找到
  • 500 服务端错误
  • 400 客户端有语法错误

设置状态码

res.writeHead(状态码)
  1. 内容类型
  • text/html
  • text/css
  • application/javascript
  • image/jpeg
  • application/json

设置内容类型

res.wirteHead(200,{
	'content-type': 'text/html;charset=utf8'
});

HTTP请求与响应处理

GET请求参数

//引入url模块
const url = require('url')
//第一个参数:要解析的url地址
//第二个参数:将查询参数解析成对象形式
//利用对象解构的方式解构出query和pathname
let { query, pathname } = url.parse(req.url, true);
console.log(query.name);
console.log(query.age);

if (pathname == "/index" || req.url == "/") {
	res.end("welcome to indexPage");
} else if (pathname == "/list") {
	res.end("welcome to listPage");
} else {
	res.end("404 Not Found");
}

POST请求参数

const http = require("http");
const app = http.createServer();
//处理请求参数模块
const querystring = require("querystring");
app.on("request", (req, res) => {
  //post参数是通过事件的方式接受的
  //当请求参数传递的时候触发data事件
  //当参数传递完成的时候触发end事件
  let postParams = "";
  req.on("data", (param) => {
    postParams += param;
  });
  req.on("end", () => {
    console.log(querystring.parse(postParams));
  });
  res.end("ok");
});
app.listen(3001);
console.log("服务器启动成功,监听3001端口");

路由

//1.引入系统模块http
//2.创建网站服务器
//3.为网站服务器对象添加请求事件
//4.实现路由功能
//  1.获取客户端的请求方式
//  2.获取客户端的请求地址
const http = require("http");
const app = http.createServer();
const url = require("url");
app.on("request", (req, res) => {
  const method = req.method.toLowerCase();
  const pathname = url.parse(req.url).pathname;

  res.writeHead(200, {
    "content-type": "text/html;charset=utf8",
  });
  if (method == "get") {
    if (pathname == "/" || pathname == "/index") {
      res.end("欢迎来到首页");
    } else if (pathname == "/list") {
      res.end("欢迎来到列表页");
    } else {
      res.end("您访问的页面不存在");
    }
  } else if (method == "post") {
  }
});
app.listen(3000);
console.log("服务器启动成功,监听3000端口");

静态资源

服务器端不需要处理,可以直接响应给客户端的资源就是静态资源,例如CSS、JavaScript、image文件

静态文件访问

const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");
const mime = require("mime");
const app = http.createServer();
app.on("request", (req, res) => {
  let pathname = url.parse(req.url).pathname;
  //当访问时不加后缀时默认访问一个网页
  pathname = pathname == "/" ? "/default.html" : pathname;
  //将用户的请求路径转换为实际的服务器硬盘路径
  let realPath = path.join(__dirname, "public" + pathname);
  let type = mime.getType(realPath);
  fs.readFile(realPath, (error, result) => {
    if (error != null) {
      res.writeHead(404, {
        "content-type": "text/html;charset=utf8",
      });
      res.end("文件读取失败");
      return;
    }
    //因为无法确定返回资源的类型,需要先引入mime(npm install mime)模块,使用mime的getType方法获取到文件类型
    res.writeHead(200, {
      "content-type": type,
    });
    res.end(result);
  });
});
app.listen(3000);
console.log("服务器启动成功");

动态资源

相同的请求地址不同的响应资源,这种资源就是动态资源

http://www.baidu.com/passage?id=1

http://www.baidu.com/passage?id=2

原文地址:https://www.cnblogs.com/actorhuang/p/13745615.html