在开发阶段很多时候需要使用到跨域。
目前解决跨域主要的方案有:

  1. jsonp (逐渐淘汰)
  2. cors (主流)
  3. http proxy

devServer解决跨域,其实原理就是http proxy。
将所有ajax请求发送给devServer服务器,再由devServer服务器做一次转发,发送给数据接口服务器。
由于ajax请求是发送给devServer服务器的,所以不存在跨域,而devServer由于是用node平台发送的http请求,自然也不涉及跨域问题,可以完美解决。

服务器端代码(返回一段字符串即可)

  1. const express = require('express')
  2. cosnt app = express()
  3. // const cors = require('cros')
  4. // app.use(cors())
  5. app.get('/api/getUserInfo', (req, res) => {
  6. res.send({
  7. name: 'Mango',
  8. age: 18
  9. })
  10. })
  11. app.listen(9999)

前端配置

前端需要配置 devServer 的 proxy 功能,在 webpack.dev.js 中进行配置:

  1. devServer: {
  2. open: true,
  3. hot: true,
  4. compress: true,
  5. proxy: {
  6. // 当请求 /api/getUserInfo 时,会转发为 http://localhost:9999/api/getUserInfo
  7. '/api': 'http://localhost:9999',
  8. // 第二种配置方式
  9. // target 目标
  10. // pathRewrite 对路径进行重写
  11. '/api': {
  12. target: 'http://localhost:9999',
  13. pathRewire: {
  14. '^/api': '' // 当请求/api/getUserInfo 时,会转发为 http://localhost:9999/getUserInfo
  15. }
  16. }
  17. }
  18. }