搭建一个简易的http服务,我这里记录两种方式:
我这里默认你已经安装了
nodejs
方案①:json-server
// 1. json-server官方文档
https://github.com/typicode/json-server
// 2. 全局安装一下
npm install -g json-server
// 3. 创建一个db.json文件,写入以下内容
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
// 4. db.json同级cmd窗口下 ,运行命令
json-server --watch db.json
效果截图:
方案②:自己用nodejs写一个基本的服务
- 运行命令
npm init -y
npm i express
npm i body-parser
- 新建文件 app.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const router = express.Router()
// 跨域请求处理
app.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'X-Requested-With')
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With, X_Requested_With')
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
//允许接收的请求头上加上一个Authorization,这样我们才能够将数据发送过去
res.header('X-Powered-By', '3.2.1')
// OPTIONS类型的请求 复杂请求的预请求
if (req.method == 'OPTIONS') {
res.send(200)
} else {
/*让options请求快速返回*/
next()
}
})
router.get('/', (req, res) => {
res.send('Hello World')
})
router.get('/tomato', (req, res) => {
res.send({
test: 1
})
})
// 挂载处理post请求的插件
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// 挂载路由
app.use(router)
// 监听5000端口 启动服务
app.listen('5000', () => {
console.log('Server is running 5000');
})
- 启动
# 在app.js同级 cmd窗口下 运行
node app.js
效果截图: