2019-10-16 記錄iview-admin 跨域問題解決失敗

今天嘗試iview-admin前端解決本地測(cè)試跨域問題,查了很多資料都寫要在vue.config.js中設(shè)置devServer代理,但是我以如下方式設(shè)置代理后,將本地開發(fā)環(huán)境的baseUrl設(shè)置為空后,并不會(huì)向代理地址發(fā)送請(qǐng)求,而仍向本地iview-admin運(yùn)行的地址發(fā)送請(qǐng)求,各種嘗試后還是沒有解決。

devServer: {
    port: port,
    open: true,
    proxy: {
      '/api': {
        target: 'http://test.com:8082/api',
        changeOrigin: true
      }
    }
  }
devServer: {
    port: port,
    open: true,
    proxy: 'http://test.com:8082/api/'
  },

后改用后臺(tái)解決跨域問題,后臺(tái)使用的是php框架laravrel
通過創(chuàng)建中間件,將本地地址加入到允許訪問的列表中,即可不配置代理直接訪問數(shù)據(jù)接口。步驟如下:
通過命令php artisan make:middleware EnableCrossRequestMiddleware創(chuàng)建一個(gè)名為EnableCrossRequestMiddleware.php的中間件,創(chuàng)建的中間件在App\Http\Middleware文件夾下,將haddle函數(shù)改為如下:

public function handle($request, Closure $next)
    {
        $response = $next($request);
        $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
        $allow_origin = [
            'http://127.0.0.1:8080',//允許訪問
            'http://localhost:8081',
            'http://192.168.0.119:8081'
        ];
        if (in_array($origin, $allow_origin)) {
            $response->header('Access-Control-Allow-Origin', $origin);
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
            $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
            $response->header('Access-Control-Allow-Credentials', 'true');
            $response->header('Access-Control-Expose-Headers', 'Authorization');
        }
        return $response;
    }

其中$allow_origin即為允許訪問的列表,將本地iview-admin運(yùn)行地址加入數(shù)組之后,再在內(nèi)核文件App\Http\Kernel.php中注冊(cè)該中間件,即可正常訪問數(shù)據(jù)接口。

protected  $middleware  =  [
        // more
       App\\Http\\Middleware\\EnableCrossRequestMiddleware::class,
];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容