前言:
本地項目在請求遠端服務器接口時,不可避免的會遇到跨域問題,即便是設置了Access-Control-Allow-Origin:* ,在遇到登錄這些需要本地存入cookie的也會很頭痛,這里筆者介紹一個在vue-cli中配置代理來解決的辦法。
在~/config/dev-server.js中 使用了非常強大的http-proxy-middleware 包。更多高級用法,請查閱其文檔。
用法:
比如我們要請求的遠端服務器為: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' } }, },
示例:
比如要請求的接口為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 createdhttp.defaults.headers.common['Authorization'] = '';export default http; /**導出http,在mainjs中引用import http from './config/axiosConfig';Vue.prototype.$http = http;**/
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
|
新聞熱點
疑難解答