对飞行前请求的响应未通过?

时间:2018-09-26 09:33:28

标签: laravel-5 http-headers react-redux

我有一个React App,它使用fetch将POST数据获取到用Laravel(PHP)编写的后端。

export const createVenue = (venueData) => dispatch => {
    console.log('action called');
           fetch('http://localhost:8001/api/venues', {
                   method: 'POST',
                   headers: {
                        'Accept': 'application/json',
                       'Content-Type': 'application/json'
                       },
                   body: JSON.stringify({
                       venueData
                   })
               })
               .then(res=>res.json())
               .then(venue=>
            dispatch({
                type: NEW_VENUE,
                payload: venue
            })
            );
};

并且我在服务器上设置了带有路由的中间件,以接受CORS请求,如下所示:

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')
         ->header('Access-Control-Allow-Headers', 'Content-Type');
    }

}

以下是路线:

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

    Route::get('venues',[
    'as' => 'apiVenueGet',
    'uses' => 'Api\Venue@index'
    ]);
    Route::post('venues',[
    'as' => 'apiVenuePost',
    'uses' => 'Api\Venue@create'
    ]);

});

但是当我用来提交数据时,我是在浏览器的控制台中得到的:

Failed to load http://localhost:8001/api/venues: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

现在,如果我在fetch调用中使用以下标头,则可以解决此问题:

headers: {
           'Accept': 'application/json',
           'Content-Type': 'text/plain'
           },

或使用application/x-www-form-urlencoded

有人可以解释为什么application/json在这里不起作用吗?

1 个答案:

答案 0 :(得分:1)

  

有人可以解释为什么application / json在这里不起作用吗?

请参见MDN

  

Content-Type标头的唯一允许值为:

     
      
  • application / x-www-form-urlencoded
  •   
  • multipart / form-data
  •   
  • 文本/纯文本
  •   

…其他任何事情都需要预检OPTIONS请求。

您仅配置了将中间件应用于GET和POST请求的路由。