詳解Vue 開發(fā)模式下跨域問題
設置請求頭部
- 后端設置請求頭部
Access-Control-Allow-Credentials: true
和Access-Control-Allow-Origin: www.xxx.com
- 前端post請求設置
withCredentials=true
- 這里用了axios的請求數(shù)據(jù)方法代碼如下:
import axios from 'axios' import config from '../config' export default { request (method, uri, data, headerConfig = {withCredentials: true}) { if (!method) { console.error('API function call requires method argument') return } if (!uri) { console.error('API function call requires uri argument') return } let url = config.serverURI + uri return axios({ method, url, data, ...headerConfig }) } }
jQuery的$.ajax::
$.ajax({ type: "POST", url: "http://www.xxx.com/api.php", dataType: 'json', xhrFields: { withCredentials: true }, crossDomain: true }).then((json) => { // balabala... })
使用nodejs做代理
- 上面的那種方法需要后端配合設置頭部,對于我這種前端小白來講,聯(lián)調時各種不成功的報錯也無從解決,所以個人比較傾向于下面這種做法,鑒于使用腳手架vue-cli創(chuàng)建的項目,作者已經給我提供好了解決的方法。
- 找到項目文件夾下的config/index.js, 里面有一行proxyTable: {}, 這里就是作者為我們留的接口, 我們添加代理規(guī)則進去
var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../xxx/index.html'), assetsRoot: path.resolve(__dirname, '../xxx'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, productionGzip: false, productionGzipExtensions: ['js', 'css'] }, dev: { env: require('./dev.env'), port: 8080, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target: 'http://www.xxx.com/api.php/', changeOrigin: true, pathRewrite: { '^/api': '/' } } }, cssSourceMap: false } }
這里target為目標域名,pathRewrite為轉換規(guī)則,請求數(shù)據(jù)時將接口地址 根據(jù)轉換規(guī)則請求就可以解決跨域啦?。ㄟ@里也可以配置headers,設置cookis,token等)
jsonp
jsonp也是一種解決跨域的方法,不過我從來沒有用過,在網(wǎng)上查了下資料,jsonp的原理是script標簽引入js是不受域名限制的, 由于是模擬插入script標簽, 所以不可以用post請求。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue + Element UI 實現(xiàn)權限管理系統(tǒng)之菜單功能實現(xiàn)代碼
菜單管理是一個對菜單樹結構的增刪改查操作,這篇文章主要介紹了Vue + Element UI 實現(xiàn)權限管理系統(tǒng)之菜單功能實現(xiàn)代碼,需要的朋友可以參考下2022-02-02vue 數(shù)據(jù)遍歷篩選 過濾 排序的應用操作
這篇文章主要介紹了vue 數(shù)據(jù)遍歷篩選 過濾 排序的應用操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11ElementUI?select彈窗在特定場合錯位問題解決方案
這篇文章主要介紹了ElementUI?select彈窗在特定場合錯位問題解決方案,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01使用sessionStorage解決vuex在頁面刷新后數(shù)據(jù)被清除的問題
localStorage沒有時間期限,除非將它移除,sessionStorage即會話,當瀏覽器關閉時會話結束,有時間期限,具有自行百度。本文使用的是sessionStorage解決vuex在頁面刷新后數(shù)據(jù)被清除的問題,需要的朋友可以參考下2018-04-04利用vue對比兩組數(shù)據(jù)差異的可視化組件詳解
這篇文章主要給大家介紹了關于利用vue對比兩組數(shù)據(jù)差異的可視化組件的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用vue具有一定的參考學習價值,需要的朋友可以參考下2021-09-09