現在LaravelでAPIを開発していますが、ライブラリを使用してもCORSが解決できません。
Dockerを使用せずにAPIを起動しましたが、こちらもダメでした。
一様、直接ブラウザやPostmanでのアクセスでは、正常にレスポンスが返ってきました。
GitHubリポジトリ
https://github.com/kbc18a11/mimawarikunapi
使用技術
- Docker-Compose: 3
- Laravel:8.22.1
docker-compose.yml
yaml
1version: "3" 2 3services: 4 php: 5 container_name: php 6 build: ./php 7 ports: 8 - 8080:80 9 volumes: 10 - ./api:/var/www 11 12 nginx: 13 image: nginx 14 container_name: nginx 15 ports: 16 - 8085:80 17 volumes: 18 - ./api:/var/www 19 - ./nginx/default.conf:/etc/nginx/conf.d/default.conf 20 depends_on: 21 - php 22 23 db: 24 image: mysql:5.7 25 container_name: db 26 env_file: ./.env 27 environment: 28 MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD 29 MYSQL_DATABASE: $MYSQL_DATABASE 30 MYSQL_USER: $MYSQL_USER 31 MYSQL_PASSWORD: $MYSQL_PASSWORD 32 TZ: "Asia/Tokyo" 33 command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci 34 volumes: 35 - ./db/data:/var/lib/mysql 36 - ./db/my.cnf:/etc/mysql/conf.d/my.cnf 37 - ./db/sql:/docker-entrypoint-initdb.d 38 ports: 39 - 3306:3306 40
Kernel.php
php
1<?php 2 3namespace App\Http; 4 5use Illuminate\Foundation\Http\Kernel as HttpKernel; 6 7class Kernel extends HttpKernel 8{ 9 /** 10 * The application's global HTTP middleware stack. 11 * 12 * These middleware are run during every request to your application. 13 * 14 * @var array 15 */ 16 protected $middleware = [ 17 \Fruitcake\Cors\HandleCors::class, 18 // \App\Http\Middleware\TrustHosts::class, 19 \App\Http\Middleware\TrustProxies::class, 20 \App\Http\Middleware\PreventRequestsDuringMaintenance::class, 21 \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, 22 \App\Http\Middleware\TrimStrings::class, 23 \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, 24 ]; 25 26 /** 27 * The application's route middleware groups. 28 * 29 * @var array 30 */ 31 protected $middlewareGroups = [ 32 'web' => [ 33 \App\Http\Middleware\EncryptCookies::class, 34 \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, 35 \Illuminate\Session\Middleware\StartSession::class, 36 \Laravel\Jetstream\Http\Middleware\AuthenticateSession::class, 37 \Illuminate\View\Middleware\ShareErrorsFromSession::class, 38 \App\Http\Middleware\VerifyCsrfToken::class, 39 \Illuminate\Routing\Middleware\SubstituteBindings::class, 40 ], 41 42 'api' => [ 43 'throttle:api', 44 \Illuminate\Routing\Middleware\SubstituteBindings::class, 45 ], 46 ]; 47 48 /** 49 * The application's route middleware. 50 * 51 * These middleware may be assigned to groups or used individually. 52 * 53 * @var array 54 */ 55 protected $routeMiddleware = [ 56 'auth' => \App\Http\Middleware\Authenticate::class, 57 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 58 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 59 'can' => \Illuminate\Auth\Middleware\Authorize::class, 60 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 61 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, 62 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 63 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 64 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 65 //'cors' => \App\Http\Middleware\Cors::class, 66 ]; 67} 68
api.php
php
1<?php 2 3use Illuminate\Http\Request; 4use Illuminate\Support\Facades\Route; 5 6/* 7|-------------------------------------------------------------------------- 8| API Routes 9|-------------------------------------------------------------------------- 10| 11| Here is where you can register API routes for your application. These 12| routes are loaded by the RouteServiceProvider within a group which 13| is assigned the "api" middleware group. Enjoy building your API! 14| 15*/ 16 17Route::group(['middleware' => ['api']], function () { 18 Route::post('/register', 'UserController@store'); 19 20 //ログイン 21 Route::post('/login', 'AuthController@login'); 22 Route::post('/logout', function (Request $request) { 23 return response()->json(['result' => 'ログアウトしました']); 24 }); 25 26 27 Route::get('/user', 'UserController@index'); 28 29 Route::get('/room', 'RoomController@index'); 30 Route::get('/room/{id}', 'RoomController@show'); 31 Route::post('/room', 'RoomController@store'); 32 Route::put('/room/{id}', 'RoomController@update'); 33});
APIリクエストの実験用のJS
javascript
1async function getRoomInfo(url = '') { 2 let headers = { 'Content-Type': 'application/json', token: 'W3F9gkQpgaRjNairZdToCugR4KtydOLmzVQfbOwqFiuoRpwqAY1RSflIAMRM' }; 3 try { 4 const response = await (await fetch(url, { mode: 'no-cors', headers: headers })).text(); 5 } catch (error) { 6 console.error('Error:', error) 7 } 8} 9function setRoomInfo() { 10 getRoomInfo('http://localhost:8085/api/room') 11 /*.then(res => res.json()) 12 .then((json)=>{ 13 this.setState({roomInfo:json}) 14 }) 15 .catch(error => { 16 console.error('Error:', error) 17 }) 18 */ 19} 20 21window.onload = () => { 22 setRoomInfo(); 23 const url = 'http://127.0.0.1:8085/api/room'; 24 let headers = { 'Content-Type': 'application/json', token: 'W3F9gkQpgaRjNairZdToCugR4KtydOLmzVQfbOwqFiuoRpwqAY1RSflIAMRM' }; 25 fetch('http://localhost:8085/api/room', { headers: headers }) 26 .then((res) => { 27 28 console.log(res); 29 res.json(); 30 }) 31 .then((json) => { 32 console.log(json); 33 }) 34 .catch(error => { 35 console.error('Error:', error); 36 }); 37 38 39 axios.defaults.headers.common = { 40 token: 'W3F9gkQpgaRjNairZdToCugR4KtydOLmzVQfbOwqFiuoRpwqAY1RSflIAMRM' 41 }; 42 axios.get(url) 43 .then(function (response) { 44 45 console.log(response); 46 }) 47 .catch(function (error) { 48 console.log(error); 49 console.log(error.response); 50 }); 51};
APIリクエストの実験用のJSの結果
localhostと127.0.0.1:8085が混ざっていますが、こちらは両方とも試した後です。
そのため、axiosとfetch両方ともlocalhostと127.0.0.1:8085で試しましたが、画像のエラーが表示されました。
また、Laravel内でも、APIリクエストの実験用のJSと同じようなものを作り、同じポートで実行しましたが、そちらも画像のエラーが表示されました。
回答2件
あなたの回答
tips
プレビュー