本篇主要介绍如何借助node的http模块和fs模块进行本地服务搭建
创建目录
在A,B,C,D,E盘随便一个你喜欢的位置创建一个文件夹,这个文件夹就是我们项目的根目录(下同)
创建index.js
在根目录下创建index.js文件,用来发送请求
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>testServer</title><script src="./jquery.min.js"></script> //引入jquery</head><body>用户名:<span id="userName"></span><script>$.ajax({url: 'http://localhost:3000/api/user', //之前使用koa2写好的APItype: 'POST',dataType: 'json',data: {user_id: 6 //查询用户ID为6的用户},success: function (res) {$('#userName').html(res.data.user_name);}})</script></body></html>
创建server.js
在根目录下创建server.js文件,用来创建服务器及异步读取文件
var http = require('http'); //引入http模块var fs = require('fs'); //引入文件读取模块//需要访问的文件的存放目录var documentRoot = 'D:/dev/todolist_fe/server';/*** 创建 http 服务器* @param http.createServer([options][, requestlistener])* @returns 新建的 http.Server 实例*/http.createServer(function (req, res) {var url = req.url;//客户端输入的url,例如如果输入localhost:8888/index.html//那么这里的url == /index.htmlvar file = documentRoot + url;/*** 异步读取文件* @param fs.readFile(filename, [encoding], [callback(err,data)])*/fs.readFile(file, function (err, data) {/*filename 文件路径options option对象,包含 encoding,编码格式,该项是可选的。callback 回调,传递2个参数 异常err 和 文件内容data*/if (err) {res.writeHeader(404, {'content-type': 'text/html;charset="utf-8"'});res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');res.end();} else {res.writeHeader(200, {'content-type': 'text/html;charset="utf-8"'});res.write(data); //将index.html显示在客户端res.end();}});}).listen(8888); //设置端口号console.log('服务器开启成功');


