在我的Laravel应用中,我设置了一条捕获所有路线来处理CORS飞行前请求。
Route::options('/{any}', 'v1\ApiController@handleCors')->where('any', '.*');
这转到执行此操作的函数:
return response()
->json($data, $this->statusCode)
->header('Accept', '*/*')
->header('Access-Control-Request-Headers', 'Content-Type, Authorization')
->header('Access-Control-Allow-Origin', 'https://frontend.myapp.com')
->header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT, OPTIONS');
现在,当我使用OPTIONS
请求调用路由时,我将获得所有标头。然后在终端中运行以下命令:
curl -i -X OPTIONS -H "Origin: https://frontend.myapp.com" \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: Content-Type, Authorization' \
"https://api.myapp.com/testingcors"
我收到以下答复:
HTTP/1.1 403 Forbidden
Server: nginx
Date: Mon, 28 Oct 2019 15:29:48 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/7.3.10
Cache-Control: no-cache, private
Origin not allowed%
当我让实际的前端与API通讯时,它将引发相同的错误。我在这里做什么错了?
答案 0 :(得分:0)
我相信CORS标头通常应用于应用实例,而不是响应。
// set the CORS headers in your app
header('Access-Control-Request-Headers', 'X-Requested-With,content-type');
header('Access-Control-Allow-Origin', 'https://frontend.myapp.com');
header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT, OPTIONS');
// return a response normally
return response()->json($data, $this->statusCode);