欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2017年06月06日 11:28:08   作者:HeiheiLqq  
本篇文章主要介紹了Vue 開發(fā)模式下跨域問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

設置請求頭部

  1. 后端設置請求頭部Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin: www.xxx.com
  2. 前端post請求設置withCredentials=true
  3. 這里用了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做代理

  1. 上面的那種方法需要后端配合設置頭部,對于我這種前端小白來講,聯(lián)調時各種不成功的報錯也無從解決,所以個人比較傾向于下面這種做法,鑒于使用腳手架vue-cli創(chuàng)建的項目,作者已經(jīng)給我提供好了解決的方法。
  2. 找到項目文件夾下的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請求。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論