douchao5864 2017-02-08 20:23 采纳率: 100%
浏览 117
已采纳

在laravel 5.3中设置cors

So I have the following middle ware:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {

        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }

}

Seems simple, its registered:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        // ...
        \App\Http\Middleware\Cors::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'cors' => \App\Http\Middleware\Cors::class,
        // ...
    ];
}

The route uses it:

Route::group([
    'prefix'     => 'api/v1/',
    'middleware' => 'cors'
], function() {
    // ...
});

Yet the console states:

Fetch API cannot load http://examplesite.local/api/v1/blogs?_sort=id&_order=DESC&_start=0&_end=10. Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

last I checked this was the proper way to set up cors in Laravel 5.3, So unless I am horribly mistaken ....

I can click the link for the api request in the net work tab of chrome and it opens a new tab showing me the result of the api, which is a json response.

yet javascript assumes that cors is not enabled?

  • 写回答

1条回答 默认 最新

  • douya7309 2017-02-08 23:28
    关注

    Looking at the last line of your error I guess you are missing the content-type header in your server side. Try adding this line to your headers and see if it works:

    header->('Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin');
    

    You could also have a look at this answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分