使用@vue/cli搭建前端项目跑在8080端口,后端使用的是moco server跑在8081端口。准备通过axios实现跨域,已经执行了以下步骤:
// main.js
// 配置baseURL
const http = axios.create({ baseURL: "/api" });
// 挂载
Vue.prototype.$http = http;
// vue.config.js
module.exports = {
devServer: {
port: 8080,
proxy: {
"/api": {
ws: false,
target: "http://localhost:8081",
changeOrigin: true
}
}
}
};
到这一步,在http://localhost:8080/api/...可以看见moco server提供的数据。
所有的接口都打算整理都api文件夹,以文章详情为例:
// api/index.js
const api = {
Article: "/articles"
};
export default api;
// api/article.js
import api from "./index";
const axios = this.$http;
export function getArticleDetail(id) {
return axios({
url: `${api.Article}/${id}`,
method: "get"
});
}
然后在页面直接调用getArticleDetail()
但是文章详情页提示:
[vue-router] Failed to resolve async component default: TypeError: Cannot read property '$http' of undefined
我想知道是不是我使用this.$http的方法错了呢?为什么没有识别?还是说整个跨域的方法都错了?希望大家路过可以指导一下,谢谢!