服務器告訴瀏覽器:你容許我跨域
具體如何告訴瀏覽器,請看:php
// 告訴瀏覽器,只容許 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', '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);
將以上代碼寫入中間件:webpack
// /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', '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; } }
在路由上添加跨域
中間件,告訴客戶端:服務器容許跨域請求web
$api->group(['middleware'=>'cors','prefix'=>'doc'], function ($api) { $api->get('userinfo', \App\Http\Controllers\Api\UsersController::class.'@show'); })
欺騙瀏覽器,讓瀏覽器以爲你沒有跨域(其實仍是跨域了,用的是代理)
在manifest.json
裏添加以下代碼:ajax
// manifest.json "devServer" : { "port" : 9000, "disableHostCheck" : true, "proxy": { "/api/doc": { "target": "http://www.baidu.com", "changeOrigin": true, "secure": false }, "/api2": { ..... } }, },
捕獲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"去向服務器請求數據
代理的API地址,就是須要跨域的API地址。 地址能夠是域名,如:http://www.baidu.com 也能夠是IP地址:http://127.0.0.1:9000 若是是域名須要額外添加一個參數changeOrigin: true,不然會代理失敗。
路徑重寫,也就是說會修改最終請求的API路徑。 好比訪問的API路徑:/api/doc/userinfo, 設置pathRewrite: {'^/api' : ''},後, 最終代理訪問的路徑:"http://www.baidu.com/doc/userinfo", 將"api"用正則替換成了空字符串, 這個參數的目的是給代理命名後,在訪問時把命名刪除掉。
這個參數能夠讓target參數是域名。
secure: false,不檢查安全問題。 設置後,能夠接受運行在 HTTPS 上,能夠使用無效證書的後端服務器
https://webpack.docschina.org/configuration/dev-server/#devserver-proxy
json
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 });