Reputation: 209
I'm building a webapp with React and Flask and I have an issue with POST request.
This is my app.py
file:
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='[email protected]', recipients=['[email protected]'])
msg.body = formated_email['textbody']
msg.html = formated_email['htmlbody']
mail.send(msg)
return 'done'
if __name__ == "__main__":
app.run()
In the config.py
I have this set CORS_HEADERS = 'Content-Type'
When I test this with Postman, my email is sent without any issue. But from the app, I get a 405 METHOD NOT ALLOWED
response.
This is how I send the request:
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!")});
This is what I have:
Since I put a proxy in place, I don't see preflights request anymore.
I tried with a simple fetch
or use superagent
but issue is still here, and I clearly don't understand how CORS works. Any help would be appreciated. Thanks!
Upvotes: 0
Views: 5104
Reputation: 209
If anyone needs the answer: issue was in the way I was sending the request with axios. Instead of:
axios.post(API_URL + 'process_email/', {...
I have to remove the trailing / ! This works fine:
axios.post(API_URL + 'process_email', {...
Upvotes: 2