Axios POST 方法:不允许使用 405 方法

时间:2021-04-12 19:54:47

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

我正在使用 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!")});

这就是我所拥有的:

enter image description here

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

1 个答案:

答案 0 :(得分:0)

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

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

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

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