[绝对有效]axios的CORS跨域限制问题解决方法

axios工具的CORS限制问题解决方法

你是否有这样的困惑:在网上看到很多介绍解决axios的跨域限制问题办法,但自己按步骤操作下来为啥没效果呢? 根源在于没讲清楚如何才能让vue.config.js文件被自动加载生效。本文就来说说这个问题。
在这里插入图片描述

解决 HTTP(S)的CORS限制问题实际上是利用 vue内部的代理转发功能,可以在vue.config.js配置文件中进行配置,而想要让vue.config.js在运行npm run dev时自动加载就需要安装@vue/cli-service才可以,这也是很多人创建了vue.config.js文件后仍然无法使用解决CORS问题的原因。

Vue官方文档中就有这样的说明:

vue.config.js 是一个可选的配置文件,如果项目的 (和 package.json 同级的) 根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。你也可以使用 package.json 中的 vue 字段,但是注意这种写法需要你严格遵照 JSON 的格式来写。

接下来要确保我们项目中已经安装了@vue/cli-service(不同项目创建方式可能安装的模块都不太一样):

$ npm list
[email protected] ./vue-demo01
├── @babel/[email protected]
├── @babel/[email protected]
├── @vue/[email protected]
├── @vue/[email protected]
├── @vue/[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

上面显示我们已经添加了@vue/cli-service包,若没有,我们可以安装一下:

npm install --save @vue/cli-service

接下来,我们才能常使用vue.config.js配置文件。

首先,编辑项目根目录下的 vue.config.js配置文件,添加内容如下:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
      '/apis': {
        target: 'https://localhost/',
        changOrigin: true,
        ws: true,
        secure: false,
        pathRewrite: {
          '^/apis': ''
        },
        logLevel: 'debug'
      }
    }
  }
})

主要添加的是devServer.proxy配置信息, 将 /apis/.xxxxx路径请求做如下处理:

  • 域名替换成 https://localhost/ ,这是访问的目标api服务主机
  • 并且将/apis删除掉(替换为空),这样比如访问 /apis/search/keyword就变成了https://localhost/search/keyword目标地址了。

接下来,修改src/main.js文件,添加内容如下:

import { createApp } from 'vue'
import axios from 'axios'
import App from './App.vue'

const app = createApp(App)
axios.defaults.baseURL = '/'
app.config.globalProperties.$axios = axios

app.mount('#app')

主要目的有两个:

  1. 设置axios默认路径为’/’ ,比如axios访问路径 api/v1/search 实际会将 baseUrl 添加在最前面,变成了 /api/v1/search了 。
  2. 设置$axios变量,这样我们在其他组件中可以全局使用 $axios调用API接口了。

最后一步就是实现一个 API调用事件,我们在APP.vue文件中做了如下修改:

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <br />
  <form @submit.prevent="onSubmit()">
    <input type="text" name="q" v-model="searchText" />
    <button type="submit">搜索</button>
  </form>

</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    // HelloWorld
  },
  data() {
    return {
      searchText: ''
    }
  },
  methods: {
    //提交查询表单
    onSubmit() {
      console.log('提交查询表单' + this.searchText)
      // 发送请求
      this.$axios.get('apis/api/v1/search/' + this.searchText + '/0').then(response => {
        console.log(response)
      })
    }
  }
}
</script>

当我们输入搜索关键词后按回车开始调用API查询并获取结果,当然这里只是简单的对返回结果进行了打印处理。

下面是一个成功调用的结果:

image-20220816235458249

vite创建项目的CORS跨域问题解决方法

Vite创建的项目,需要配置vite.config.js,内容类似下面:

export default defineConfig({
    
    
  server: {
    
    
    proxy: {
    
    
      "/api": {
    
    
        target: "https://localhost",
        changeOrigin: true,
        secure: false,
        // rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  plugins: [vue()]
})

配置后重启一下服务就可以生效了。

最后

到这里,如果解决了你的问题也好让我也知道,替你开心开心。欢迎一键三十连哈,我是悟空。

猜你喜欢

转载自blog.csdn.net/dragonballs/article/details/126384996