国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

詳解Vue 開發(fā)模式下跨域問題

2024-05-06 15:16:16
字體:
供稿:網(wǎng)友

設(shè)置請(qǐng)求頭部

    后端設(shè)置請(qǐng)求頭部Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin: www.xxx.com 前端post請(qǐng)求設(shè)置withCredentials=true 這里用了axios的請(qǐng)求數(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 + urireturn 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做代理

    上面的那種方法需要后端配合設(shè)置頭部,對(duì)于我這種前端小白來講,聯(lián)調(diào)時(shí)各種不成功的報(bào)錯(cuò)也無從解決,所以個(gè)人比較傾向于下面這種做法,鑒于使用腳手架vue-cli創(chuàng)建的項(xiàng)目,作者已經(jīng)給我提供好了解決的方法。 找到項(xiàng)目文件夾下的config/index.js, 里面有一行proxyTable: {}, 這里就是作者為我們留的接口, 我們添加代理規(guī)則進(jìn)去
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為目標(biāo)域名,pathRewrite為轉(zhuǎn)換規(guī)則,請(qǐng)求數(shù)據(jù)時(shí)將接口地址 根據(jù)轉(zhuǎn)換規(guī)則請(qǐng)求就可以解決跨域啦!(這里也可以配置headers,設(shè)置cookis,token等)

jsonp

jsonp也是一種解決跨域的方法,不過我從來沒有用過,在網(wǎng)上查了下資料,jsonp的原理是script標(biāo)簽引入js是不受域名限制的, 由于是模擬插入script標(biāo)簽, 所以不可以用post請(qǐng)求。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長站。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 临沭县| 尉犁县| 缙云县| 滨海县| 乌拉特前旗| 汝州市| 昌乐县| 屯昌县| 华亭县| 汤原县| 阳信县| 磐石市| 工布江达县| 娄底市| 屯昌县| 房产| 左云县| 丁青县| 缙云县| 德阳市| 涿州市| 通榆县| 曲靖市| 肇庆市| 游戏| 银川市| 巨鹿县| 宜兴市| 银川市| 皋兰县| 洞口县| 兴化市| 榆林市| 顺平县| 惠州市| 揭西县| 中超| 肥东县| 喀什市| 定陶县| 屏边|