搭建环境
首先新建blog-1文件夹,在文件夹下初始化package.json,执行命令:
npm init -y
生成的package.json文件中的main属性默认值index.js改成bin/www.js(即是在工程目录下新建bin文件夹,并在下面新建一个www.js)
- 1.安装nodemon监听文件变化;
- 2.安装cross-env设置环境变量。
npm i nodemon cross-env -D
package.json代码中的scripts下添加新属性dev,值如下:
{ "name": "blog-1", "version": "1.0.0", "description": "", "main": "bin/www.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "cross-env": "^7.0.3", "nodemon": "^2.0.12" } }
在工程文件下新建app.js:
const serverHandle = (req,res) => { res.setHeader(‘Content-type‘,‘application/json‘); resData = { name: ‘xiaomo10000‘, site: ‘localhost‘, dev: process.env.NODE_ENV } res.end(JSON.stringify(resData)); } module.exports = serverHandle;
www.js代码如下:
const http = require(‘http‘) const PORT = 8000 const serverHandle = require(‘../app‘); const server = http.createServer(serverHandle); server.listen(PORT)
执行命令:npm run dev,在地址栏输入:http://localhost:8000/,打开控制台 就能看到请求后相应的内容如下:
{"name":"xiaomo10000","site":"localhost","dev":"dev"}