当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 详解Vuejs2.0 如何利用proxyTable实现跨域请求

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

垃圾短信智能盾,杨明鑫,甜点图片

前言:

本地项目在请求远端服务器接口时,不可避免的会遇到跨域问题,即便是设置了access-control-allow-origin:* ,在遇到登录这些需要本地存入cookie的也会很头痛,这里笔者介绍一个在vue-cli中配置代理来解决的办法。

在~/config/dev-server.js中 使用了非常强大的包。更多高级用法,请查阅其。

用法:

比如我们要请求的远端服务器为: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'
    }
   },
  },
  • 通过设置changeorigin:true 开启代理
  • pathrewrite 意为重写路径

示例:

比如要请求的接口为http://192.168.400:3000/api/main/getuserinfo.action

this.$http.post('/api/main/getuserinfo.action')
 .then(res=>{
  console.log(res)
 })

后续:

在实际工作中,我们还需要做些其他的,比如在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;
**/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网