搭建一个简易的http服务,用于前端调试。

搭建一个简易的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 

效果截图:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lazy_tomato

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值