1. 问题引入
最近有个需求就是使用vue读取我服务器上的data.json数据,然后通过vue里面的axios来读取,但是在实现这个需求的过程中出现了下面这个错误:
错误大致描述为:
'访问XMLHttpRequest'http://*.*.*.*/data.json“来源”http://localhost:8080'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origin'标头
2.解决方案
顺着上面的提示的错误我就是这样进行搜索解决方案的:
然后浏览器出现了一大堆解决方案,看了一些方案感觉针对我这个问题没多大的用处,所以我直接来说解决我这个问题的这种方法。
2.1 新建vue.config.js
在自己的根目录下新建vue.config.js
module.exports = {
devServer: {
open: true,
host: 'localhost',
port: 8080,
https: false,
hotOnly: false,
// http 代理配置
proxy: {
'/api': {
target: 'http://172.22.121.12:66666',//(填写自己的地址)
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
2.2 修改main.js里面的一些属性
import Vue from 'vue'
import App from './App'
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import VueRouter from 'vue-router'
import routers from './router'
import store from "@/store";
import axios from 'axios'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false
Vue.use(Antd);
Vue.use(ElementUI);
const router = new VueRouter({
mode: 'history',
routes: routers
})
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
// 需要把这个注释掉,直接用vue.config.js里的api替代如下所示
// axios.defaults.baseURL = 'http://172.22.121.12:66666'
// 设置响应时间5秒
axios.defaults.timeout = 5000
// 核心代码
axios.get('/api/data.json')
.then(function (response) {
console.log(1111111)
console.log(response);
})
.catch(function (error) {
console.log(222222)
console.log(error);
});
3. 效果展示
通过上面的方法我们刷新下页面之后出现下面的结果就说明我们成功了。