You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Facebook Messenger访问时出现405 Method Not Allowed错误求助

排查Flask应用对接Facebook Messenger时的405 Method Not Allowed错误

Hey there, let's break down why you're hitting that 405 error and how to fix it quickly!

What's causing the 405 error?

The core issue is a request method mismatch. Facebook Messenger sends POST requests to your webhook when delivering messages or events, but your current Flask route (@app.route('/')) only accepts GET requests by default. That's why the server is rejecting the request with "Method Not Allowed".

Step 1: Update your Flask route to support POST (and GET for verification)

Flask's route decorator needs explicit permission to accept POST requests. Here's how to adjust your code:

from flask import Flask, request, jsonify

app = Flask(__name__, template_folder='./')

@app.route('/', methods=['GET', 'POST'])  # Add both GET and POST methods here
def index():
    # Handle Facebook's webhook verification (GET request)
    if request.method == 'GET':
        # Replace with the verify token you set in Facebook Developer Dashboard
        YOUR_VERIFY_TOKEN = "your_custom_verify_token"
        received_token = request.args.get('hub.verify_token')
        if received_token == YOUR_VERIFY_TOKEN:
            # Return the challenge value to complete verification
            return request.args.get('hub.challenge')
        else:
            return "Invalid verification token", 403
    
    # Handle incoming Messenger messages/events (POST request)
    elif request.method == 'POST':
        # Parse the incoming JSON data from Messenger
        incoming_data = request.get_json()
        
        # Add your message processing logic here (e.g., reply to messages)
        
        # Return a 200 OK response to let Messenger know you received the data
        return jsonify({"status": "success"}), 200

Step 2: Double-check your Facebook Webhook configuration

  • Make sure the Webhook URL in your Facebook Developer Dashboard points exactly to this Flask route (e.g., https://your-deployed-domain.com/)
  • Confirm the Verify Token in the dashboard matches the YOUR_VERIFY_TOKEN value in your code
  • Ensure you've subscribed to the necessary Webhook events (like messages, messaging_postbacks) under the Webhook settings

Step 3: Additional checks for production

  • If you're deploying with a server like Gunicorn or Nginx, make sure it's not blocking POST requests to your route
  • Test locally with a tool like Postman: send a POST request to http://localhost:5000/ with sample JSON to confirm your route responds correctly

内容的提问来源于stack exchange,提问作者tapas r Mohanty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:41:01