1. 程式人生 > 程式設計 >詳解vue或uni-app的跨域問題解決方案

詳解vue或uni-app的跨域問題解決方案

常見解決方案有兩種

伺服器端解決方案

伺服器告訴瀏覽器:你允許我跨域

具體如何告訴瀏覽器,請看:

// 告訴瀏覽器,只允許 http://bb.aaa.com:9000 這個源請求伺服器
$response->header('Access-Control-Allow-Origin','http://bb.aaa.com:9000');
// 告訴瀏覽器,請求頭裡只允許有這些內容
$response->header('Access-Control-Allow-Headers','Authorization,Content-Type,Depth,User-Agent,X-File-Size,X-Requested-With,X-Requested-By,If-Modified-Since,X-File-Name,X-File-Type,Cache-Control,Origin');
// 告訴瀏覽器,只允許暴露'Authorization,authenticated'這兩個欄位
$response->header('Access-Control-Expose-Headers',authenticated');
// 告訴瀏覽器,只允許GET,POST,PATCH,PUT,OPTIONS方法跨域請求
$response->header('Access-Control-Allow-Methods','GET,OPTIONS');
// 預檢
$response->header('Access-Control-Max-Age',3600);

將以上程式碼寫入中介軟體:

// /app/Http/Middleware/Cors.php
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;
class Cors {

  /**
   * Handle an incoming request.
   *
   * @param \Illuminate\Http\Request $request
   * @param \Closure $next
   * @return mixed
   */
  public function handle($request,Closure $next)
  {
    $response = $next($request);
    // 告訴瀏覽器,只允許 http://bb.aaa.com:9000 這個源請求伺服器
    $response->header('Access-Control-Allow-Origin','http://bb.aaa.com:9000');
    // 告訴瀏覽器,請求頭裡只允許有這些內容
    $response->header('Access-Control-Allow-Headers',Origin');
    // 告訴瀏覽器,只允許暴露'Authorization,authenticated'這兩個欄位
    $response->header('Access-Control-Expose-Headers',authenticated');
    // 告訴瀏覽器,只允許GET,OPTIONS方法跨域請求
    $response->header('Access-Control-Allow-Methods',OPTIONS');
    // 預檢
    $response->header('Access-Control-Max-Age',3600);
    return $response;
  }

}

在路由上新增跨域中介軟體,告訴客戶端:伺服器允許跨域請求

$api->group(['middleware'=>'cors','prefix'=>'doc'],function ($api) {
  $api->get('userinfo',\App\Http\Controllers\Api\UsersController::class.'@show');
  
})

客戶器端解決方案

欺騙瀏覽器,讓瀏覽器覺得你沒有跨域(其實還是跨域了,用的是代理)

在manifest.json裡新增如下程式碼:

// manifest.json
"devServer" : {
  "port" : 9000,"disableHostCheck" : true,"proxy": {
    "/api/doc": {
      "target": "http://www.baidu.com","changeOrigin": true,"secure": false
    },"/api2": {
     .....
    }
  },},

引數說明

'/api/doc'

捕獲API的標誌,如果API中有這"/api/doc"個字串,那麼就開始匹配代理,
比如API請求"/api/doc/userinfo",
會被代理到請求 "http://www.baidu.com/api/doc"
即:將匹配到的"/api/doc"替換成"http://www.baidu.com/api/doc"
客戶端瀏覽器最終請求連結表面是:"http://192.168.0.104:9000/api/doc/userinfo",
實際上是被代理成了:"http://www.baidu.com/api/doc/userinfo"去向伺服器請求資料

target

代理的API地址,就是需要跨域的API地址。
地址可以是域名,如:http://www.baidu.com
也可以是IP地址:http://127.0.0.1:9000
如果是域名需要額外新增一個引數changeOrigin: true,否則會代理失敗。

pathRewrite

路徑重寫,也就是說會修改最終請求的API路徑。
比如訪問的API路徑:/api/doc/userinfo,
設定pathRewrite: {'^/api' : ''},後,
最終代理訪問的路徑:"http://www.baidu.com/doc/userinfo",
將"api"用正則替換成了空字串,
這個引數的目的是給代理命名後,在訪問時把命名刪除掉。

changeOrigin

這個引數可以讓target引數是域名。

secure

secure: false,不檢查安全問題。
設定後,可以接受執行在 HTTPS 上,可以使用無效證書的後端伺服器

其他引數配置檢視文件
https://webpack.docschina.org/configuration/dev-server/#devserver-proxy

請求封裝

uni.docajax = function (url,data = {},method = "GET") {
 return new Promise((resolve,reject) => {
  var type = 'application/json'
  if (method == "GET") {
   if (data !== {}) {
    var arr = [];
    for (var key in data) {
     arr.push(`${key}=${data[key]}`);
    }
    url += `?${arr.join("&")}`;
   }
   type = 'application/x-www-form-urlencoded'
  }
  var access_token = uni.getStorageSync('access_token')
  console.log('token:',access_token)
  var baseUrl = '/api/doc/'
  uni.request({
   url: baseUrl + url,method: 'GET',data: data,header: {
    'content-type': type,'Accept':'application/x..v1+json','Authorization':'Bearer '+access_token,success: function (res) {
    if (res.data) {
     resolve(res.data)
    } else {
     console.log("請求失敗",res)
     reject(res)
    }
   },fail: function (res) {
    console.log("發起請求失敗~")
    console.log(res)
   }
  })
 })
}

請求示例:

//獲取使用者資訊
uni.docajax("userinfo",{},'GET')
.then(res => {
  this.nickname = res.nickname
  this.avatar = res.avatar
});

到此這篇關於詳解vue或uni-app的跨域問題解決方案的文章就介紹到這了,更多相關vue或uni-app的跨域問題解決方案內容請搜素我們以前的文章或下面相關文章,希望大家以後多多支援我們!