【问题标题】:Axios POST Method: 405 Method Not AllowedAxios POST 方法:405 方法不允许
【发布时间】:2021-07-07 22:00:35
【问题描述】:

我正在使用 React 和 Flask 构建一个 web 应用程序,但我遇到了 POST 请求问题。

这是我的app.py 文件:

import sys
import os

from flask import Flask, jsonify, request, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS, cross_origin
from flask_mail import Mail, Message

from models import User, Project, Image, db
from api import blueprints
from tools import format_email


app = Flask(__name__,
  static_folder='../build/static',
  template_folder="../build"
)

app.config.from_object(os.environ['APP_SETTINGS'])
db.init_app(app)
cors = CORS(app)
mail = Mail(app)

# Register the blueprints
for b in blueprints:
  app.register_blueprint(b)

@cross_origin
@app.route('/', defaults={'u_path': ''})
@app.route('/<path:u_path>')
def index(u_path=None):
  return render_template("index.html")


@app.route('/api/process_email', methods=['POST'])
def process_email():
  print('plop')
  data = request.get_json()
  formated_email = format_email(
    data['firstname'],
    data['lastname'],
    data['email'],
    data['message']
  )
  msg = Message(formated_email['title'], sender='plop@gmail.com', recipients=['plop@gmail.com'])
  msg.body = formated_email['textbody']
  msg.html = formated_email['htmlbody']
  mail.send(msg)

  return 'done'

if __name__ == "__main__":
  app.run()

config.py我有这套CORS_HEADERS = 'Content-Type'

当我使用 Postman 进行测试时,我的电子邮件发送没有任何问题。但是从应用程序中,我收到了405 METHOD NOT ALLOWED 的回复。

这是我发送请求的方式:

axios.post(API_URL + 'process_email/', {
      "firstname": values.firstname,
      "lastname": values.lastname,
      "email": values.email,
      "message": values.message
    }, {
      headers: {
        'Content-Type': 'text/plain;charset=utf-8',
      },
      withCredentials: 'same-origin'
    })
    .then(({ data }) => {
          console.log(data)
      }, (error) => {
        toast.error("gneuuuu");
      })
      .catch(() => {toast.error("Oups! Something went wrong!")});

这就是我所拥有的:

自从我设置了代理后,我再也看不到预检请求了。 我尝试使用简单的fetch 或使用superagent,但问题仍然存在,我显然不明白 CORS 是如何工作的。任何帮助,将不胜感激。谢谢!

【问题讨论】:

    标签: python reactjs flask post http-status-code-405


    【解决方案1】:

    如果有人需要答案:问题在于我使用 axios 发送请求的方式。而不是:

    axios.post(API_URL + 'process_email/', {...

    我必须删除尾随的 / !这工作正常:

    axios.post(API_URL + 'process_email', {...

    【讨论】:

      猜你喜欢
      • 2020-07-25
      • 2021-12-12
      • 2014-05-23
      • 2018-12-20
      • 2015-11-16
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多