create-react-app跨域配置

1,506 阅读1分钟

跨域配置

1.package.json配置

// 新版本中只能写这种
"proxy": "http://172.16.136.249:8080"

// 新版本的react不支持这种写法
"proxy": {
    "/api/**": {
      "target": "http://172.16.136.249:8080",
      "changeOrigin": true
    }
  }

2.通过middleware中间件的方式设置proxy

需要使用middleware,通常来说create-react-app会自动帮我们下载好的,如果没有下载好的话,请使用如下命令

yarn add http-proxy-middleware --save
或
npm install http-proxy-middleware --save

安装middleware插件后,在src目录中新建setupProxy.js文件,在文件中放入如下代码:

const { createProxyMiddleware } = require('http-proxy-middleware')

// 通常使用这种方式就够了,如果报错,可以使用下面的方法
module.exports = function (app) {
    app.use(
        proxy('/api1', {     // 遇见/api1开头的请求,触发改代理配置
            target: 'http://172.16.136.249:8080',       // 请求转发给谁
            secure: false,
            changeOrigin: true,     // 控制服务器收到的请求头中的Host值,默认false,意思为服务端收到的Host值是我们自己本的地址,开启以后,服务端收到的就会他自己的地址
            pathRewrite: {
              "^/api1": "/api"      // 把所有/api1重写成api
            }
        }),
        proxy('/api2', {
            target: 'http://172.16.136.250:8080',
            secure: false,
            changeOrigin: true,
            pathRewrite: {
              "^/api2": "/api"
            }
        })
    )
}

module.exports = function (app) {
    app.use(
        createProxyMiddleware('/api', {
            target: 'http://172.16.136.249:8080',
            secure: false,
            changeOrigin: true,
            pathRewrite: {
              "^/api": "/api"
            }
        })
    )
}

3.额外说一种,服务端是Node写的情况 需要在Node中安装cors的中间件

yarn add cors --save
或
npm install cors --save

项目中使用

const express = require('express')
const app = express()
const request = require('request')
const fs = require('fs')
// 跨域.  CROS配置 ---------- Start
const cors = require('cors');

app.use(cors({
  origin: ['http://172.16.136.249:3000'], // 所要允许跨域的ip
  methods: ['GET', 'POST'],
  alloweHeaders: ['Conten-Type', 'Authorization']
}));
// 跨域.  CROS配置 ---------- End

app.post('/api/getdata', (req, res) => {
  let data = fs.readFileSync('./data/data.json')

  console.log('数据', data.toString())

  res.send(data.toString())
})

app.listen(8080, () => {
  console.log('服务运行成功')
})