Solution to CORS limitation problem of axios tool
Do you have this kind of confusion: I saw a lot of introductions on the Internet to solve the cross-domain restriction problem of axios, but why did it not work after following the steps by myself? The root cause is that it is not clear how to make
vue.config.js
the file be automatically loaded to take effect. This article will talk about this problem.
Solving the CORS restriction problem of HTTP(S) is actually using the proxy forwarding function inside vue, which can vue.config.js
be configured in the configuration file, but if you want to automatically load vue.config.js
at runtime , npm run dev
you need to install it @vue/cli-service
, which is why many people created vue.config.js
the file After still can't use to solve the reason of CORS problem.
There is such a description in the official Vue documentation:
vue.config.js is an optional configuration file. If this file exists in the root directory of the project (similar to package.json), it will be automatically loaded by @vue/cli-service. You can also use the vue field in package.json, but note that this way of writing requires you to strictly follow the JSON format.
Next, make sure that it is installed in our project @vue/cli-service
(different project creation methods may install different modules):
$ 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]
The above shows that we have added @vue/cli-service
the package, if not, we can install it:
npm install --save @vue/cli-service
Next, we can often use vue.config.js
configuration files.
First, edit the vue.config.js configuration file in the root directory of the project , and add the following content:
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'
}
}
}
})
The main addition is
devServer.proxy
configuration information, and/apis/.xxxxx
the path request is processed as follows:
- Replace the domain name with
https://localhost/
, this is the target api service host to visit- And it will
/apis
be deleted (replaced with empty), so that, for example,/apis/search/keyword
access becomeshttps://localhost/search/keyword
the target address.
Next, modify src/main.js
the file and add the following content:
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')
There are two main purposes:
- Set the default path of axios to '/'. For example, the access path of axios will
api/v1/search
actually add the baseUrl at the front and become/api/v1/search
.- Set
$axios
the variable so that we can use it globally in other components$axios
to call API interface.
The last step is to implement an API call event, we APP.vue
made the following changes in the file:
<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>
When we enter the search keyword and press Enter, we start calling the API query and get the results. Of course, the returned results are simply printed here.
Here is the result of a successful call:
Solution to CORS cross-domain problem of vite creation project
The project created by Vite needs to be configured vite.config.js
, and the content is similar to the following:
export default defineConfig({
server: {
proxy: {
"/api": {
target: "https://localhost",
changeOrigin: true,
secure: false,
// rewrite: (path) => path.replace(/^\/api/, ""),
},
},
},
plugins: [vue()]
})
After configuration, restart the service to take effect.
at last
Come here, if your problem is solved, let me know, happy for you. Welcome to Lianha 三十
, I am Wukong.