解决Vu3 axios 跨域问题 Vue CORS错误
错误信息
跨域错误
Access to XMLHttpRequest at ‘http://localhost:5000/v2/Scene/Quiz’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
main.js 中axios的请求配置
import axios from 'axios'
axios.defaults.baseURL='http://localhost:5000/v2/Scene/'
Vue.prototype.$http=axios
接口请求代码
async getTestDate(){
console.log('123')
const {data:res}=await this.$http.get('Quiz')
console.log(res)
console.log('123')
}
错误更改
1.在与package.json 同级目录下创建vue.config.js文件
2.在vue.config.js文件中输入以下代码
module.exports ={
devServer: {
host: 'localhost',
port: 8080, //没被占用,可以使用的端口
open: true,
proxy: {
'/api':{
target: 'http://localhost:5000/v2/Scene/', //接口域名
changeOrigin: true, //是否跨域
secure: true, //是否https接口
pathRewrite: { //路径重置
'^/api': ''
}
}
}
}
}
3.在main.js文件中修改代码
import axios from 'axios'
axios.defaults.baseURL='/api'
Vue.prototype.$http=axios
修改axios.defaults.baseURL=‘http://localhost:5000/v2/Scene/’ 为 axios.defaults.baseURL=’/api’
完成后记得重启项目,即可运行