你也许用得上的生产预览、接口代理 & mock接口

117 阅读2分钟

create-react-app生产预览

  1. 安装
npm i nodemon express
  1. package.json里添加命令并启动服务 npm run serve,其中server为根目录下执行的js文件
"serve": "nodemon server"
  1. server.js
const path = require('path')
const express = require('express')
const app = express()
// 监听路由并托管静态文件
app.use('/', express.static(path.join(__dirname, 'build')))
app.listen(5000, () => {
    console.log("server running at http://localhost:5000")
})

开发环境mock接口

  1. package.json里添加命令并启动服务 npm run json,其中json为根目录下执行的js文件
"json": "nodemon json"
  1. json.js
const express = require('express')
const createError = require('http-errors')
const app = express()
app.use(express.json())
app.all("*", (req, res, next) => {
  //设置允许跨域的域名,*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
  //跨域允许的请求方式 
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // 可以带cookies
  res.header("Access-Control-Allow-Credentials", true);
  if (req.method == 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
})
// 也可以更换请求方式
app.get('/api/json', (req, res) => {
  // 报文
  let data = {
    code: 1,
    msg: '请求成功',
    data: {
    name: '咸鱼翻身',
    age: 58
  }}
  res.send(data)
})
app.use((req, res, next) => {
  next(createError(404))
})
app.use((err, req, res, next) => {
  let result = {
    code: 0,
    msg: err.message,
    err: err.stack
  }
  res.status(err.status|| 500).json(result)
})

app.listen(7000, () => {
    console.log("server running at http://localhost:7000")
})

调用接口:

fetch(`http://localhost:7000/api/getInfo`, {
      method: 'get',
      mode: 'cors'
    }).then(res => {
      let result = res.json()
      result.then(data => {
        console.log(data)
      })
    })

效果预览:

1.png

最后,修改下直接读取json文件(数据来源掘金//api.juejin.cn/tag_api/v1/query_category_briefs接口)

const path = require('path') 
const fs = require('fs')
const express = require('express')
const createError = require('http-errors')
const app = express()
app.use(express.json())
app.all("*", (req, res, next) => {
  //设置允许跨域的域名,*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
  //跨域允许的请求方式 
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // 可以带cookies
  res.header("Access-Control-Allow-Credentials", true);
  if (req.method == 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
})
app.get('/api/getInfo', (req, res, next) => {
  // 报文
  // let data = {
  //   code: 1,
  //   msg: '请求成功',
  //   data: {
  //   name: '咸鱼翻身',
  //   age: 58
  // }}
  // res.send(data)
  // 读取根目录下modal.json文件
  fs.readFile(path.join(__dirname, 'modal.json'), (err, data) => {
    if(err) {
      next(err)
    }
    // 二进制转字符串
    const result = data.toString('utf-8');
    res.send(result)
  })
})
app.use((req, res, next) => {
  next(createError(404))
})
app.use((err, req, res, next) => {
  let result = {
    code: 0,
    msg: err.message,
    err: err.stack
  }
  res.status(err.status|| 500).json(result)
})

app.listen(7000, () => {
    console.log("server running at http://localhost:7000")
})

效果预览:

1.png

开发环境代理

  1. create-react-app
  • 安装 http-proxy-middleware
npm i http-proxy-middleware
  • src目录下添加setupProxy.js
const {createProxyMiddleware} = require('http-proxy-middleware')
module.exports = function(app) {
    app.use('/__api__', (...args) => {
        return createProxyMiddleware({
            target: 'https://hope.demogic.com', // 目标域名
            changeOrigin: true,
            secure: false,
            pathRewrite: { [`^/__api__`]: '' }
        })(...args)
    })
}
  • 页面请求
function Proxy(url: string) {
    if (process.env.NODE_ENV === 'production') {
      return url
    } else { // 开发环境替换
      return `/__api__`
    }
  }
const logout = async () => {
    try {
      const res = await Axios.get(`${Proxy(`//dopen.weimob.com`)}/open-api/user/getToken.json?appKey=&appSecret=`, {
        withCredentials: true,
        timeout: 5000
      })
      console.log(res, '-------世界分割线-----')
    } catch (error) {
      
    }
}
  1. Vite代理 vite.config.ts
server: {
    proxy: {
          '/__api__': {
            target: 'https://hope.demogic.com',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/__api__/, '')
          }
          // 多个代理同上
          // '': {}
    }
}

请求:

export function Proxy(url: string, api: string) {
  if (import.meta.env.MODE === 'development') {
    return api
  } else {
    return url
  }
}
export async function demogic_token() {
  return await Axios.get(`${Proxy(`//dopen.weimob.com`, '__api__')}/demogic/open-api/user/getToken.json?appKey=&appSecret=`, {
    withCredentials: true,
    timeout: 5000
  })
}