dingo / dingo/api

Problems integrating CORS

Open
#1,469 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
PHP
Stars
9.4k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

| Q | A
| ----------------- | ---
| Bug? | no
| New Feature? | no
| Framework | Lumen
| Framework version | v5.4.7
| Package version | v1.0.0-beta8
| PHP version | 7.0.x

#### Actual Behaviour

Initially installed `barryvdh/laravel-cors` to add CORS-Headers to every response. Since this wasn't working (tried all fixes suggested in issues of both dingo and laravel-cors repos) I ended up adding a custom middleware to be able to respond to HEAD/OPTIONS requests:
```
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{

//Intercepts OPTIONS requests
if($request->isMethod('OPTIONS') || $request->isMethod('HEAD')) {
$response = response('', 200);
} else {
// Pass the request to the next middleware
$response = $next($request);
}

// Adds headers to the response
$response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
$response->header('Access-Control-Allow-Origin', '*');

// Sends it
return $response;
}
}
```

#### Expected Behaviour

CORS headers are now added as expected and API stopped responding with 405 errors for OPTIONS/HEAD requests.

However, all responses now show `HEAD, GET, POST, PUT, PATCH, DELETE` as allowed methods, which is not the case for many resources. Is there a way to access the dingo routing table from the middle to extract the registered methods to provide a dynamic list of allowed methods?

Thanks!

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.