此方案只能用于开发环境, 线上最好设置同源策略
前后端不在同一服务器的情况下, 前端要访问后端 API, 可通过在 vue.config.JS 中配置代理服务器.
0: 前提条件
1: 安装 vue-lic
2: 安装 axios 用于发送请求.
1: 将任何未知请求转发到代理服务器
如:
前端地址: 127.0.0.1
后端地址: 127.0.0.2
当访问地址为 127.0.0.1/API, 没有匹配到这地址, 那么就会被转发到代理服务器 127.0.0.2/API
- module.exports={
- devServer:{
- proxy: "http://www.acfun.cn" http://www.acfun.cn%22/ ;
- }
- }
2: 多代理控制
更多代理服务配置项搜索 http-proxy-middleware 查看
- module.exports = {
- devServer: {
- proxy: {
- '/search': {
- // search 为转发路径
- target: 'http://www.acfun.cn/', // 目标地址
- ws: true, // 是否代理 websockets
- changeOrigin: true // 设置同源 默认 false, 是否需要改变原始主机头为目标 URL,
- }
- }
- }
- };
如:
当前访问地址为 xxx.xxx.xxx/search 时, 就会被转发到代理服务器 http://www.acfun.cn/search
xxx.xxx.xxx/search -> http://www.acfun.cn/search
3: 实例
API.JS 文件 (主要用于全局配置)
- import Axios from "axios";
- let http = Axios.create({
- timeout: 3000, // 超时配置 3 秒
- responseType: 'json', // 响应数据格式
- responseEncoding: 'utf8', // 响应数据编码
- });
- export default http;
入口文件 main.JS
- import Vue from "vue";
- import App from "./App.vue";
- import router from "./router";
- import http from "./api"; // 引用 axios 全局配置
- Vue.config.productionTip = false;
- Vue.prototype.$http = http; // 添加原型方法, 这样创建的对象就自带该方法了.
- new Vue({
- router,
- render: h => h(App)
- }).$mount("#app");
vue.config.JS 配置文件
更多代理服务配置项搜索 http-proxy-middleware 查看
- module.exports = {
- devServer: {
- proxy: {
- '/search': {
- target: 'http://www.acfun.cn/',
- ws: true,// 是否代理 websockets
- changeOrigin: true // 设置同源 默认 false, 是否需要改变原始主机头为目标 URL
- }
- }
- }
- };
然后在 vue 实例对象中直接访问 $http 方法就行.
来源: http://www.qdfuns.com/article/51759/7298856e43a055d3ce11eafd1220d5bc.html