源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

详解Vuejs2.0 如何利用proxyTable实现跨域请求

  • 时间:2020-05-10 14:16 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:详解Vuejs2.0 如何利用proxyTable实现跨域请求
[b]前言:[/b] 本地项目在请求远端服务器接口时,不可避免的会遇到跨域问题,即便是设置了Access-Control-Allow-Origin:* ,在遇到登录这些需要本地存入cookie的也会很头痛,这里笔者介绍一个在vue-cli中配置代理来解决的办法。 在~/config/dev-server.js中 使用了非常强大的[url=https://github.com/chimurai/http-proxy-middleware]http-proxy-middleware [/url]包。更多高级用法,请查阅其[url=https://github.com/chimurai/http-proxy-middleware#options]文档[/url]。 [b]用法:[/b] 比如我们要请求的远端服务器为:http://192.168.400:3000
proxyTable: {
   '/api/': {
    target: 'http://192.168.400:3000',
    changeOrigin:true,  //set the option changeOrigin to true for name-based virtual hosted sites
    pathRewrite: {
     '^/api': '/api'
    }
   },
  },
[list] [*]通过设置changeOrigin:true 开启代理[/*] [*]pathRewrite 意为重写路径[/*] [/list] [b]示例:[/b] 比如要请求的接口为http://192.168.400:3000/api/main/getUserInfo.action
this.$http.post('/api/main/getUserInfo.action')
 .then(res=>{
  console.log(res)
 })
[b]后续:[/b] 在实际工作中,我们还需要做些其他的,比如在axios中配置baseUrl:
/**
 * Created by Administrator on 2017/4/11.
 */
import axios from 'axios';

// 添加响应拦截器
axios.interceptors.request.use(function (config) {
 // 配置发送请求的信息

 return config;
}, function (error) {
 return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
 // 配置请求回来的信息

 return response;
}, function (error) {
 return Promise.reject(error);
});

var http = axios.create({
 timeout: 8000, /*设置请求超时时间*/
 baseURL:'http://192.168.400:3000', 

});

// Alter defaults after instance has been created
http.defaults.headers.common['Authorization'] = '';

export default http; 

/**导出http,在mainjs中引用
import http from './config/axiosConfig';
Vue.prototype.$http = http;
**/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部