[英]Axios POST Method: 405 Method Not Allowed
我正在使用 React 和 Flask 構建一個 webapp,但我遇到了 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 測試這個時,我的 email 發送沒有任何問題。 但是從應用程序中,我得到了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 是如何工作的。 任何幫助,將不勝感激。 謝謝!
如果有人需要答案:問題在於我使用 axios 發送請求的方式。 代替:
axios.post(API_URL + 'process_email/', {...
我必須刪除尾隨/:這很好用:
axios.post(API_URL + 'process_email', {...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.