記錄一次解決Vue跨域請求接口404問題

前端使用VUE
接口使用 laravel
服務(wù)器用的是寶塔

1.修改laravel的cors,添加一個cors的中間件
2.需要nginx的反向代理,(nginx.conf配置文件)

  • laravel 操作:https://www.cnblogs.com/phpk/p/10923128.html
    中間件
    在 Laravel 中允許跨域請求,我們可以在app/Http/Middleware/文件夾下構(gòu)建一個追加響應(yīng)的中間件Cors.php,用來添加專門處理跨域的請求的響應(yīng)頭:
<?php
namespace App\Http\Middleware;

use Closure;
use 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);
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
        $response->header('Access-Control-Allow-Credentials', 'false');
        return $response;
    }

}

使用中間件
在app/Http/Kernel.php文件中protected $routeMiddleware處增加'cors' => \App\Http\Middleware\Cors::class,。


image.png

需要跨域請求的路由:

Route::group(['middleware'=>'cors'], function() {
    Route::any('/send','SendController@index');
});

nginx操作:https://blog.csdn.net/weixin_44692055/article/details/103693859
如果是配置了多個站點域名,需要找到nginx的子配置文件
寶塔一般在:/www/server/panel/vhost/nginx/ 路徑下面
文件名一般都是域名

location   /api{
        proxy_pass http://xxxx.com;
        add_header Content-Type "text/plain;charset=utf-8";
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST';
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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