通过虚拟代理服务器解决Axios跨域问题[Vue.js项目实践: 新冠自检系统]

Logo

新冠疫情自我检测系统网页设计开发文档

Sylvan Ding 的第一个基于 Vue.js 的项目. 本项目所提供的信息,只供参考之用,不保证信息的准确性、有效性、及时性和完整性,更多内容请查看国家卫健委网站!
Explore the docs »

View Demo · Report Bug · Request Feature

homepage

通过虚拟代理服务器解决Axios跨域问题

A cross-domain problem happened when a client requests data from the server. Since direct cross-domain access using axios is not feasible, we need to configure the proxy.

A proxy server requests data from another server, and then the server returns the requested data to the proxy server, and the proxy server returns the data to the client.

开发环境

node14.16.1
npm8.18.0
vue-cli2.9.6
vue2.5.2

解决方案

In the proxyTable field in the index.js file under the config folder, add the following rule:

// config/index.js

const port = 8080
const devServerPort = 8081

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/': {
        target: `http://localhost:${devServerPort}/static/mock`,
        changeOrigin: true, // override the origin of the host header
        pathRewrite: {
          '^/': '', // replace the request address in the target
        },
      },
    },
    // ...
  }
  // ...
}

Now axios will replace the beginning symbol / to http://localhost:${devServerPort}/static/mock in the request address. Make sure that we cancel baseURL configuration under development environment to avoid proxyTable being overridden.

// src/utils/request.js

const prodBaseURL = 'http://localhost:5000'

let axiosConfig = {
  timeout: 3000,
  // ...
}

// set baseURL under production environment
if (process.env.NODE_ENV === 'production') {
  axiosConfig.baseURL = prodBaseURL
}

const instance = axios.create(axiosConfig)

// ...

转载请注明出处:©️ Sylvan Ding 2022

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值