Skip to content
This repository has been archived by the owner on Feb 9, 2021. It is now read-only.

webpack-dev-server 代理跨域请求 / 模拟本地后端 #8

Open
lbwa opened this issue Mar 19, 2018 · 0 comments
Open

webpack-dev-server 代理跨域请求 / 模拟本地后端 #8

lbwa opened this issue Mar 19, 2018 · 0 comments
Labels
Ajax Ajax implementation ( eg. axios ) Node.js Node.js .etc

Comments

@lbwa
Copy link
Owner

lbwa commented Mar 19, 2018

我的一篇关于跨域解决方案的博文

1. 模拟本地后端

通常在前端开发的过程中,有使用 axios-mock-adapter 工具模拟后端返回的方法,本文旨在记录另一种通过配置 wepack-dev-server 来模拟后端返回数据的方法。

涉及背景知识

在 webpack 配置中 devServer.before 用于在服务器内部所有中间件执行前定义自定义处理程序,即此选项可在本地模拟服务器数据返回。

webpack-dev-serverreadme 部分有如下介绍:

Most new feature requests can be accomplished with Express middleware; please look into using the before and after hooks in the documentation.

由此,可知我们可在 webpack 中配置 devServer.before 且该方法是具有 Express 中间件的 API

配置方法

配置文件代码如下:

const appData = require('../mock/data.json') // 引入 mock 数据文件

const seller = appData.seller  // 定义不同 api 返回的数据
const goods = appData.goods
const ratings = appData.ratings

const devWebpackConfig = {
  // ...
  devServer: {
    before (app) {
      app.get('/api/seller', (req, res) => {   // 使用 app.get() 方法模拟后端
        res.json({  // 使用 res.json() 方法转换为 JSON 格式
          errno: 0,
          data: seller  // 指定地址匹配时,应返回的数据
        })
      })

      app.get('/api/goods', (req, res) => {
        res.json({
          errno: 0,
          data: goods
        })
      })

      app.get('/api/ratings', (req, res) => {
        res.json({
          errno: 0,
          data: ratings
        })
      })
    }
  }
  //...
}

示例配置

点我可见示例配置

2. 代理跨域请求

开发过程中,跨域请求真实后端接口时,因 jsonp 无法伪造 Request Header 中的 Host 和 referer,而造成 5XX 服务器错误

解决方案

可设置 devServer.before( ) ,之后让 app ajax 请求 webpack-dev-server 地址,让 webpack-dev-server 代理请求后端接口。

示例代码如下:

  devServer: {
    // app 请求 webpack-dev-server 地址
    // webpack-dev-server 代理发送 ajax 请求
    before (app) {
      app.get('/api/getPlayList', (req, res) => {
        var url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg'

        axios.get(url, {
          headers: {
            referer: 'https://c.y.qq.com',
            host: 'c.y.qq.com'
          },
          params: req.query
        }).then(response => {
          res.json(response.data)
        }, e => {
          throw Error('Proxy failed')
        })
      })
    },
    // ...
   }

示例配置

点我可见示例配置

@lbwa lbwa added Node.js Node.js .etc Ajax Ajax implementation ( eg. axios ) labels Mar 19, 2018
@lbwa lbwa changed the title 在 webpack-dev-server 中模拟后端数据返回 webpack-dev-server 代理跨域请求 / 模拟本地后端 Apr 1, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Ajax Ajax implementation ( eg. axios ) Node.js Node.js .etc
Projects
None yet
Development

No branches or pull requests

1 participant