英文:
Post request with dart to flask gives out OPTIONS with code 200
问题
Here's the modified Dart code to resolve the issue with the "OPTIONS" request when making a POST request to your Flask backend. This code sets up the necessary headers to handle CORS (Cross-Origin Resource Sharing) requests properly.
void createUser({required String email, required String password}) async {
final Map<String, String> headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*', // Add this line for CORS
};
Map<String, String> data = {
"email": email,
"password": password,
};
try {
final response = await http.post(
Uri.parse("http://localhost:5000/register"),
headers: headers,
body: json.encode(data),
);
} on Exception catch (e) {
rethrow;
}
}
The change is to add the 'Access-Control-Allow-Origin' header with the value '*' to allow requests from any origin. This should resolve the "OPTIONS" request issue when calling the createUser
method from your Flutter frontend.
Please make sure that this change complies with your CORS policy and security requirements.
英文:
I'm trying to do a post request with dart to my flask back-end, this is my post request on dart
void createUser({required String email, required String password}) async{
final Map<String, String> headers = {'Content-Type': 'application/json'};
Map<String, String> data = {
"email": email,
"password": password,
};
try {
final response = await http.post(Uri.parse("http://localhost:5000/register"), headers: headers, body: json.encode(data));
} on Exception catch (e) {
rethrow;
}
}
and this is the post flask
def post(self):
arguments = reqparse.RequestParser()
arguments.add_argument('email', type=str, required=True, help="Email is required")
arguments.add_argument('password', type=str, required=True, help="Password is required")
user_data = arguments.parse_args()
if User.find_user(user_data['email']):
return {"error": "User already exists"}, 409
user = User(**user_data)
user.save_user()
return {"message": "User created successfully"}, 201
Was able to do a post request with curl normally like this
curl -H "Content-Type: application/json" -X POST -d '{"email":"test@test.com", "password":"12345678"}' http://localhost:5000/register
But when I run it on my flutter front-end that calls the createUser method it shows this on flask terminal
127.0.0.1 - - [10/Aug/2023 17:45:59] "OPTIONS /register HTTP/1.1" 200 -
答案1
得分: 0
通过添加CORS到flask来修复
from flask_cors import CORS
app = Flask(__name__)
app.config.from_object(AppConfiguration)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
api = Api(app)
英文:
Fixed by adding CORS to flask
from flask_cors import CORS
app = Flask(__name__)
app.config.from_object(AppConfiguration)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
api = Api(app)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论