Skip to content

Commit f2f6e7b

Browse files
author
Dipesh Sukhia
committed
add cross origin support and content type json support
1 parent fe1fe78 commit f2f6e7b

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

README.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,22 @@ This package is used to generate laravel api with Resources
1313
You can install the package via composer:
1414

1515
```bash
16-
composer require bhavingajjar/laravel-api-generator --dev
16+
composer require bhavingajjar/laravel-api-generator
1717
```
1818

1919
## Publish Configuration File
2020

2121
```bash
2222
php artisan vendor:publish --provider="Bhavingajjar\LaravelApiGenerator\LaravelApiGeneratorServiceProvider" --tag="config"
23+
24+
Next, if you plan for cross origin support, you should add middleware to your api middleware group within your app/Http/Kernel.php file:
25+
'ApiHeaderInject'
26+
27+
add in env
28+
for allow cross origin support
29+
API_ALLOW_CROSS_ORIGIN = true
30+
for json content type
31+
API_JSON_RESPONSE = true
2332
```
2433
2534
## Usage

src/Middleware/ApiHeaderInject.php

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,18 @@ class ApiHeaderInject
99
{
1010
public function handle($request, Closure $next)
1111
{
12-
$response = $next($request);
1312
if(config('laravel-api-generator.json_response')) {
14-
$response = $response->headers('Content-Type', 'application/json')
15-
->header('Accept', 'application/json');
13+
$request->headers->add([
14+
'Accept'=>'application/json',
15+
'Content-Type'=>'application/json'
16+
]);
1617
}
1718
if(config('laravel-api-generator.allow_cross_origin')) {
18-
$response = $response->header('Access-Control-Allow-Origin', '*')
19-
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
19+
$request->headers->add([
20+
'Access-Control-Allow-Origin' => '*',
21+
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS'
22+
]);
2023
}
21-
return $response;
24+
return $next($request);
2225
}
2326
}

0 commit comments

Comments
 (0)