๋ผ๋ผ๋ฒจ 5.1
๋ผ๋ผ๋ฒจ ์์
2.1.0
barryvdh/laravel-cors 0.8.0
๋๋ laravel-excel์ด laravel-cor์ ์ ์๋ํ ๊ฒ์ด๋ผ๊ณ ๊ธฐ๋ํ์ต๋๋ค.
laravel-excel์ laravel-cors๋ฅผ ๋ฌด์ํ๊ณ ์๋ต์ ์ค์ ๋์ง ์์ต๋๋ค.
ํค๋ "Access-Control-Allow-Origin" ๋ฐ "Vary"
๋ค์ด๋ก๋ ๋ฐ ๋ด๋ณด๋ด๊ธฐ ๋ฐฉ๋ฒ์์ laravel-excel์ Illuminate\Http\Response๋ฅผ ์ฌ์ฉํ์ง ์์ต๋๋ค.
์ด๊ฒ์ด ๋ชจ๋ ๊ฒ์ ๊นจ๋จ๋ฆฐ ๊ฒ์
๋๊น?
www.example-a.com ์์ javascript(๋ด ๊ฒฝ์ฐ angularjs ์ ํ๋ฆฌ์ผ์ด์ )์์ www.example-b.com (laravel + laraver-cors + laravel-excel์ด ์๋ ์๋ฒ)์ผ๋ก ์์ฒญํฉ๋๋ค.
PHPExcel์ด ์ค์ ๋ค์ด๋ก๋๋ฅผ ์ฒ๋ฆฌํ๋ฏ๋ก ์ด ํจํค์ง๋ Response ์ฌ์ฉ์ ์ง์ํ์ง ์์ต๋๋ค. ํค๋๋ฅผ ์ง์ ์ ๋ฌํด์ผ ํฉ๋๋ค(๋ ๋ฒ์งธ ๋งค๊ฐ๋ณ์).
->download('xls', [yourheader])
์ด๊ฒ์ ๋ฌธ์์ ์ถ๊ฐํ์ญ์์ค.
์๋ ํ์ธ์, ์ ๋ ์ค์ ๋ก Lumen ํ๋ก์ ํธ์์ Laravel-Excel์ ์ฌ์ฉํ๊ณ ์์ผ๋ฉฐ ๋ฐ์ดํฐ๋ฅผ Excel ํ์ผ๋ก ๋ด๋ณด๋ด๊ณ ์๋์ ๊ฐ์ด ๋ค์ด๋ก๋ํ๋ ค๊ณ ํฉ๋๋ค.
๋ด ์ฌ์ฉ์๋ด๋ณด๋ด๊ธฐ :
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
/**
* <strong i="8">@return</strong> \Illuminate\Support\Collection
*/
public function collection()
{
return User::all();
}
}
๋ด ์ปจํธ๋กค๋ฌ :
public function excel()
{
return Excel::download(new UsersExport(),'users.xlsx');
}
์น.php :
$router->get('/download', 'CommunicationController<strong i="17">@excel</strong>');
๊ทธ๋ฆฌ๊ณ Excel() ํจ์๋ฅผ ์คํํ๋ ค๊ณ ํ ๋ ์ด ์ค๋ฅ๊ฐ ๋ฐ์ํฉ๋๋ค.
๊ทธ๋ฌ๋ ์ด๋ฏธ ์ค๋์ ์ CorsMiddleware.php๋ฅผ ์์ฑํ์ฌ bootstrap/app.php์ ์ถ๊ฐํ๊ณ ๋ค๋ฅธ ๋ชจ๋ ๊ธฐ๋ฅ์ ๋๋ถ์ ์ ์๋ํฉ๋๋ค.
์ฑ.php :
$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);
CorsMiddleware.php :
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* <strong i="30">@param</strong> \Illuminate\Http\Request $request
* <strong i="31">@param</strong> \Closure $next
* <strong i="32">@return</strong> mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With, api_token'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
}
๋ด๊ฐ ๋ญ๊ฐ๋ฅผ ์์๋์? ๋๋ ์ด์ ๋ถํฐ ๋ถ์ด ์์๊ณ ์ ๋ง ๋น์ ์ ๋์์ด ํ์ํฉ๋๋ค :'(
์ฌ๊ธฐ์์ ๋ด๊ฐ ์ฌ์ฉํ๋ Lumen๊ณผ maatwebsite/excel์ ๋ฒ์ ์ ๋ณผ ์ ์์ต๋๋ค.
"require": {
"php": ">=7.1.3",
"guzzlehttp/guzzle": "^6.3",
"laravel/lumen-framework": "5.7.*",
"maatwebsite/excel": "^3.1",
"phpoffice/phpspreadsheet": "^1.6",
"vlucas/phpdotenv": "~2.2"
},
๊ฐ์ฌํฉ๋๋ค!
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
PHPExcel์ด ์ค์ ๋ค์ด๋ก๋๋ฅผ ์ฒ๋ฆฌํ๋ฏ๋ก ์ด ํจํค์ง๋ Response ์ฌ์ฉ์ ์ง์ํ์ง ์์ต๋๋ค. ํค๋๋ฅผ ์ง์ ์ ๋ฌํด์ผ ํฉ๋๋ค(๋ ๋ฒ์งธ ๋งค๊ฐ๋ณ์).
->download('xls', [yourheader])