React-配置跨域

前言

跨域是什么在这里就不多说了,主要说怎么配置
Vue跨域推荐文章

步骤

package.json(第一种方式)

"proxy": "http://localhost:4000",//目标地址 

缺点:只能写一次,缺乏灵活性

setupProxy.js (第二种方式)

在src目录下新建setupProxy文件(使用CommonJs语法)

// 引入中间件
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
    
    
    app.use(
        proxy('/api', {
    
    
            target: 'http://localhost:5000',  // 目标地址
            changeOrigin: true,    // 允许跨域
            pathReWrite: {
    
    '^/api': ''}   // 正则匹配字段,路径重写
        })
    )
}

配置多个跨域

const proxy = require('http-proxy-middleware')
module.exports = function (app) {
    
    
    app.use(
        proxy('/api', {
    
    
            target: 'http://localhost:5000',
            changeOrigin: true,
            pathReWrite: {
    
    '^/api': ''}
        }),
        proxy('/api', {
    
    
            target: 'http://localhost:8000',
            changeOrigin: true,
            pathReWrite: {
    
    '^/api': ''}
        })
    )
}

猜你喜欢

转载自blog.csdn.net/qq_45859670/article/details/125996821
今日推荐