詳解vue或uni-app的跨域問題解決方案
常見解決方案有兩種
服務器端解決方案
服務器告訴瀏覽器:你允許我跨域
具體如何告訴瀏覽器,請看:
// 告訴瀏覽器,只允許 http://bb.aaa.com:9000 這個源請求服務器
$response->header('Access-Control-Allow-Origin', 'http://bb.aaa.com:9000');
// 告訴瀏覽器,請求頭里只允許有這些內(nèi)容
$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', 'Authorization, authenticated');
// 告訴瀏覽器,只允許GET, POST, PATCH, PUT, OPTIONS方法跨域請求
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, 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');
// 告訴瀏覽器,請求頭里只允許有這些內(nèi)容
$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', 'Authorization, authenticated');
// 告訴瀏覽器,只允許GET, POST, PATCH, PUT, OPTIONS方法跨域請求
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, 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": {
.....
}
},
},
參數(shù)說明
'/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"去向服務器請求數(shù)據(jù)
target
代理的API地址,就是需要跨域的API地址。
地址可以是域名,如:http://www.baidu.com
也可以是IP地址:http://127.0.0.1:9000
如果是域名需要額外添加一個參數(shù)changeOrigin: true,否則會代理失敗。
pathRewrite
路徑重寫,也就是說會修改最終請求的API路徑。
比如訪問的API路徑:/api/doc/userinfo,
設置pathRewrite: {'^/api' : ''},后,
最終代理訪問的路徑:"http://www.baidu.com/doc/userinfo",
將"api"用正則替換成了空字符串,
這個參數(shù)的目的是給代理命名后,在訪問時把命名刪除掉。
changeOrigin
這個參數(shù)可以讓target參數(shù)是域名。
secure
secure: false,不檢查安全問題。
設置后,可以接受運行在 HTTPS 上,可以使用無效證書的后端服務器
其他參數(shù)配置查看文檔
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("發(fā)起請求失敗~")
console.log(res)
}
})
})
}
請求示例:
//獲取用戶信息
uni.docajax("userinfo",{},'GET')
.then(res => {
this.nickname = res.nickname
this.avatar = res.avatar
});
到此這篇關于詳解vue或uni-app的跨域問題解決方案的文章就介紹到這了,更多相關vue或uni-app的跨域問題解決方案內(nèi)容請搜素腳本之家以前的文章或下面相關文章,希望大家以后多多支持腳本之家!
相關文章
vue中get請求如何傳遞數(shù)組參數(shù)的方法示例
這篇文章主要介紹了vue中get請求如何傳遞數(shù)組參數(shù)的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11
Vue中foreach數(shù)組與js中遍歷數(shù)組的寫法說明
這篇文章主要介紹了Vue中foreach數(shù)組與js中遍歷數(shù)組的寫法說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

