詳解Vue 開發模式下跨域問題,vue

來源:互聯網
上載者:User

詳解Vue 開發模式下跨域問題,vue

佈建要求頭部

  1. 後端佈建要求頭部Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin: www.xxx.com
  2. 前端post請求設定withCredentials=true
  3. 這裡用了axios的請求資料方法代碼如下:
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做代理

  1. 上面的那種方法需要後端配合設定頭部,對於我這種前端小白來講,聯調時各種不成功的報錯也無從解決,所以個人比較傾向於下面這種做法,鑒於使用腳手架vue-cli建立的項目,作者已經給我提供好瞭解決的方法。
  2. 找到專案檔夾下的config/index.js, 裡面有一行proxyTable: {}, 這裡就是作者為我們留的介面, 我們添加代理規則進去
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為轉換規則,請求資料時將介面地址 根據轉換規則請求就可以解決跨域啦!(這裡也可以配置headers,設定cookis,token等)

jsonp

jsonp也是一種解決跨域的方法,不過我從來沒有用過,在網上查了下資料,jsonp的原理是script標籤引入js是不受網域名稱限制的, 由於是類比插入script標籤, 所以不可以用post請求。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.