vue使用代理,axios访问接口后代理失败

原本使用axios封装

// 创建axios实例
const service = axios.create({
    baseURL: HTTP_URL, // 接口请求地址
    timeout: 10000, // 请求超时时间
    headers: {
        'content-type': 'application/json'
    },
})

在vue.config.js设置好代理

	module.exports = {
    lintOnSave: false,
    //   publicPath: process.env.NODE_ENV === 'production'
    //     ? '/mobile/'
    //     : '/',
    publicPath: '/',
    outputDir: '/dist',
    chainWebpack: config => {
        config.resolve.alias
        .set("@", resolve("src"))
        .set("@A", resolve("src/assets"))
        .set("@C", resolve("src/components"))
        .set("@V", resolve("src/views"))
        .set("@STYLES", resolve("src/styles"))
        .set("@API", resolve("src/api"))
        .set("@U", resolve("src/utils"))
        config
        .plugin('html')
        .tap(args => {
            args[0].title = '求签'
            return args
        })
    },
      //vue-cli3.0 里面的 vue.config.js做配置
    devServer: {
        open: false,
        port: 8080,
        proxy: {
        	// 因为接口请求地址是 http://xxxx.xxx.com/v1/xxx/xxx
            '/v1': {
                target: "http://xxxx.xxx.com/",  // 后台接口域名
                ws: false,        //如果要代理 websockets,配置这个参数
                secure: false,  // 如果是https接口,需要配置这个参数
                changeOrigin: true,  //是否跨域
                pathRewrite:{
                    '^/v1': '/v1'
                }
            },
        }
    }
}

配好以后发现还是跨域了,说明代理没有生效
跨域错误

解决

去掉这个配置的baseURL就行了

const service = axios.create({
    //baseURL: HTTP_URL, // 接口请求地址
    timeout: 10000, // 请求超时时间
    headers: {
        'content-type': 'application/json'
    },
})

或者将baseURL改为/v1/

const service = axios.create({
    baseURL: "/v1/", // 接口请求地址
    timeout: 10000, // 请求超时时间
    headers: {
        'content-type': 'application/json'
    },
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值