MeWrite Docs

405 Method Not Allowed

HTTPリクエストのメソッドがサーバーで許可されていない場合のエラー

概要

HTTPリクエストで使用したメソッド(GET、POST、PUT、DELETEなど)が、対象のリソースでサポートされていない場合に返されるステータスコードです。

エラーメッセージ

HTTP/1.1 405 Method Not Allowed
Allow: GET, POST
1
2
3
4
{
  "error": "Method Not Allowed",
  "message": "The method PUT is not allowed for this resource"
}

原因

  1. 間違ったHTTPメソッド: POSTすべきところをGETでリクエスト
  2. ルーティング設定: サーバー側でメソッドが許可されていない
  3. CORS: プリフライトリクエストで許可されていないメソッド
  4. リソースの制限: 特定のリソースでは一部メソッドのみ許可
  5. フレームワークの設定: ルート定義でメソッドが指定されていない

解決策

1. 正しいHTTPメソッドを使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// RESTful API の一般的なメソッド
// GET: リソースの取得
fetch('/api/users', { method: 'GET' });

// POST: リソースの作成
fetch('/api/users', {
  method: 'POST',
  body: JSON.stringify({ name: 'John' })
});

// PUT: リソースの更新(全体)
fetch('/api/users/1', {
  method: 'PUT',
  body: JSON.stringify({ name: 'John', email: 'john@example.com' })
});

// PATCH: リソースの部分更新
fetch('/api/users/1', {
  method: 'PATCH',
  body: JSON.stringify({ name: 'John Updated' })
});

// DELETE: リソースの削除
fetch('/api/users/1', { method: 'DELETE' });

2. サーバー側でメソッドを許可

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Express.js
const express = require('express');
const router = express.Router();

// 複数のメソッドを同じルートで処理
router.route('/users')
  .get(getUsers)
  .post(createUser);

router.route('/users/:id')
  .get(getUser)
  .put(updateUser)
  .delete(deleteUser);
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/users', methods=['GET', 'POST'])
def users():
    if request.method == 'GET':
        return get_users()
    elif request.method == 'POST':
        return create_user()

3. CORSでメソッドを許可

1
2
3
4
5
6
7
8
// Express.js with CORS
const cors = require('cors');

app.use(cors({
  origin: 'http://localhost:3000',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));
1
2
3
4
5
6
7
8
9
# Flask-CORS
from flask_cors import CORS

CORS(app, resources={
    r"/api/*": {
        "origins": "*",
        "methods": ["GET", "POST", "PUT", "DELETE", "PATCH"]
    }
})

4. Nginxでの設定

1
2
3
4
5
6
7
8
location /api/ {
    # 許可するメソッドを制限
    limit_except GET POST PUT DELETE {
        deny all;
    }

    proxy_pass http://backend;
}

5. Laravelでの設定

1
2
3
4
5
6
7
8
// routes/api.php
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{user}', [UserController::class, 'update']);
Route::delete('/users/{user}', [UserController::class, 'destroy']);

// または
Route::apiResource('users', UserController::class);

6. フォームでのメソッドスプーフィング

1
2
3
4
5
6
7
8
<!-- HTMLフォームはGETとPOSTのみ -->
<!-- Laravel: _methodフィールドでスプーフィング -->
<form action="/users/1" method="POST">
    @csrf
    @method('PUT')
    <input type="text" name="name" value="John">
    <button type="submit">Update</button>
</form>

7. Allowヘッダーを確認

1
2
3
4
5
6
// 405レスポンスのAllowヘッダーを確認
async function checkAllowedMethods(url) {
  const response = await fetch(url, { method: 'OPTIONS' });
  const allowed = response.headers.get('Allow');
  console.log('Allowed methods:', allowed);
}

8. クライアント側のエラーハンドリング

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
async function apiRequest(url, options) {
  const response = await fetch(url, options);

  if (response.status === 405) {
    const allowed = response.headers.get('Allow');
    throw new Error(`Method not allowed. Allowed: ${allowed}`);
  }

  return response;
}

よくある間違い

  • HTMLフォームでPUT/DELETEを直接使おうとする
  • APIドキュメントを確認せずにメソッドを選ぶ
  • GETリクエストでボディを送信しようとする
  • CORSのプリフライトでメソッドが拒否されている

関連エラー

参考リンク

HTTP の他のエラー

最終更新: 2025-12-13