我正在从angular到flask进行API调用。在烧瓶中,我得到的是[OPTIONS]而不是[POST]。如果我两次调用相同的API,那么烧瓶将把它识别为[POST]方法。
这是烧瓶代码:
import numpy as np
import pickle
from flask import Flask, request, redirect
from flask.json import jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
app = Flask(__name__)
cors = CORS(app, resources={r"*": {"origins": "*"}})
app.secret_key = "Secret Key"
model = pickle.load(open('model.pkl', 'rb'))
#API Calls
@app.route('/',methods=["GET"])
def index():
if request.method == "GET":
return jsonify(data="Hello World")
@app.route('/login',methods=['POST'])
def login():
if request.method == 'POST':
data = request.get_json()
return jsonify(data),200
@app.route('/register',methods=["POST"])
def register():
if request.method == 'POST':
data = request.get_json()
email = data["email"]
username = data["displayName"]
password = data["password"]
res = {
"result" : "success"
}
return jsonify(res),200
if __name__ == "__main__":
app.run(debug=True)
这是Angular中的API服务:
export class ApiService {
constructor(private http: HttpClient) {}
getHeaders(method: string) {
const token = localStorage.getItem("token");
const headers: any = {};
if (method === "post") {
headers["Content-type"] = "application/json";
}
return {
headers: new HttpHeaders(headers),
};
}
get(url: string) {
const headers = this.getHeaders("get");
return this.http.get(`${environment.apiUrl}${url}`, headers).toPromise();
}
post(url: string, payload: Object) {
const headers = this.getHeaders("post");
return this.http
.post(`${environment.apiUrl}${url}`, payload, headers)
.toPromise();
}
}
这是我点击注册按钮时调用的方法:
constructor(private api: ApiService, private router: Router) {}
ngOnInit(): void {}
async register(email: string,password: string,passwordCheck: string, displayName: string)
{
const newUser = {
email,
password,
passwordCheck,
displayName,
};
try {
const result = await this.api.post("/register", newUser);
console.log(result)
this.router.navigate(["/login"]);
} catch (err) {
console.log(err);
}
}
烧瓶中的终端输出:
127.0.0.1 - - [17/Jun/2021 09:48:14] "OPTIONS /register HTTP/1.1" 200 -
127.0.0.1 - - [17/Jun/2021 09:48:19] "POST /register HTTP/1.1" 200 -
"检查"中的"网络"选项卡:寄存器
谢谢。
嗨,我也有同样的问题。问题是浏览器将发送一个";飞行前";使用OPTION方法请求。这是更多信息https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.如果这在客户端给你带来了CORS问题,我解决了它,捕获请求并验证方法是否为OPTIONS,并向OPTION-请求的响应添加一些头:
from flask import Flask, request, Response
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.before_request
def handle_preflight():
if request.method == "OPTIONS":
res = Response()
res.headers['X-Content-Type-Options'] = '*'
return res