node.js是一门服务端的语言,下面讲讲如何利用node.js提供给我们的api来搭建服务器,并且访问静态网页
项目结构如下
![](https://i-blog.csdnimg.cn/blog_migrate/91ea2bc8c8203dd4bcaa0e01eb118c43.png)
----------------------------------------------------------------
第一步
首先你得安装node环境
第二步
新建Server.js文件,将下面代码复制到该文件中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | // require这些东西都是调用node环境中的包,只要有node环境,这些require的模块都是默认被安装进去了,就可以直接这样写 // node支持ES6的写法,下面的就是ES6的写法,不需要额外使用插件来把ES6转ES5,很方便 let http = require( 'http' ) let url = require( 'url' ) let util = require( 'util' ) let fs = require( 'fs' ) // http库是node提供的api,可以直接上node的中文网,直接看到各种api let server = http.createServer((req, res) => { // 通过你在浏览器输入的网站,利用url.parse进行解析成一个对象,再读取其中pathname的属性 // 例如你输入http://localhost:8080/index.html,然后url.parse(req.url).pathname返回的值为 "/index.html" var pathname = url.parse(req.url).pathname console.log( 'file:' + pathname.substring(1)) // fs,文件系统,读取文件 fs.readFile(pathname.substring(1), (err, data) => { if (err) { // 错误就返回404状态码 res.writeHead(404, { 'Content-Type' : 'text/html' }) } else { // 成功读取文件 res.writeHead(200, { 'Content-Type' : 'text/html' }) // 展示文件数据 res.write(data.toString()) } // 注意,这个end 一定要放在读取文件的内部使用 res.end(util.inspect(url.parse(req.url))) }) }) server.listen(3000, '127.0.0.1' , () => { console.log( '服务器已经运行,请打开浏览器,输入:http://127.0.0.1:3000/来访问' ) }) |
第三步
在同级文件夹下创建一个html页面,例如index.html,代码如下
1 2 3 4 5 6 7 8 9 10 | <! DOCTYPE html> < html lang="en"> < head > < meta charset="UTF-8"> < title >Title</ title > </ head > < body > < h2 >大家快来访问我呀!</ h2 > </ body > </ html > |
第四步
使用命令行工具,进入到server文件夹,然后输入
第五步
打开浏览器,输入http://localhost:3000/index.html,访问服务器
效果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/de470e076759573608f76321fc5c7a18.png)
怎么样,一个服务器就几行代码就能成功建立起来了,并且能够通过url方式来访问对应位置的网页资源,node.js真的很简洁,很好用呀~~