laravel框架跨域问题的解决

写好了api,手机端来调用的时候,可以操作数据库,但是接收不到后端的返回值。出现了这样的情况,如果代码没有错误,那就应该是跨域的问题了。

写个中间件AllowAcross.php:

<?php

namespace App\Http\Middleware;

use Closure;

class AllowAcross
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");

        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE, PATCH',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, OriginOrigin, Cookie, Accept, multipart/form-data, application/json',
            'Access-Control-Allow-Credentials' => 'false',
        ];

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }
}

然后在kernel.php文件中配置中间件:

 protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        //这就是所加的中间件
        'allow' => \App\Http\Middleware\AllowAcross::class,

    ];

然后在routes.php中配置好路由

Route::group(['middleware'=>['allow'],'prefix'=>'api','namespace'=>'Api'],function(){
    //校对版本信息
    Route::post('version', 'IndexController@version');
    }

这样跨域问题就解决了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值