詳解Vuejs2.0 如何利用proxyTable實現跨域請求,vuejs2.0proxytable
前言:
本地項目在請求遠端伺服器介面時,不可避免的會遇到跨域問題,即便是設定了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' } }, },
- 通過設定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 createdhttp.defaults.headers.common['Authorization'] = '';export default http; /**匯出http,在mainjs中引用import http from './config/axiosConfig';Vue.prototype.$http = http;**/
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。