具有数据的发布请求导致:对预检请求的响应未通过访问控制检查:没有“ Access-Control-Allow-Origin”标头

时间:2019-03-27 18:31:16

标签: node.js laravel cors laravel-5.2 next.js

似乎当我对数据执行POST请求时,然后在控制台中收到以下错误消息:

  

访问“ http://localhost:8000/api/feedback/send/”处的XMLHttpRequest   来自来源“ http://localhost:3000”的信息已被CORS政策阻止:   对预检请求的响应未通过访问控制检查:否   请求中存在“ Access-Control-Allow-Origin”标头   资源。

所以当我发出这样的请求时,它可以正常工作:

request({
            method: 'post',
            url: `${process.env.APIURL}tags/`,
        })

但是当我执行以下请求时,它将失败并显示错误消息:

request({
            method: 'post',
            url: `${process.env.APIURL}feedback/send/`,
            data: {
                feedback: this.state.feedback,
                email: this.state.email,
            }
        })

我在localhost:3000的next.js应用正在对我在localhost:8000的laravel api发出请求。 在我的laravel应用中,我将以下cors配置设置为中间件:

public function handle($request, Closure $next) {
        if ($request->getMethod() == "OPTIONS") {
            return response(['OK'], 200, [
                'Access-Control-Allow-Origin' => 'http://localhost:3000',
                'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS, PATCH',
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, X-Auth-Token, Authorization',
            ]);
        }

        return $next($request)
            ->header('Access-Control-Allow-Origin', 'http://localhost:3000')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH')
            ->header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, X-Auth-Token, Authorization');
    }

这是我的浏览器控制台中该发布请求的结果: post request

路线注册如下:

Route::group(['middleware' => 'cors'], function () {
    Route::post('/api/feedback/send', 'FeedbackController@send');
});

如何与数据对象一起获得该错误消息?

0 个答案:

没有答案