因此,我收到一个表示CORS策略的CORS错误:所请求的资源上没有“ Access-Control-Allow-Origin”标头。问题是我的标头中确实有Access-Control-Allow-Origin。我也将CORS导入了我的python,它确实对GET请求有帮助,但对POST请求却没有帮助。
这是我的Axios。
let URL = 'http://127.0.0.1:5000/Walls/saveComments'
let HEADERS = {method: "POST","Content-Type": "application/x-www-form-urlencoded",'Access-Control-Allow-Origin': '*','Accept': 'application/json'}
let data = {
'post': post,
'time': time,
'comment': comment
}
console.log(this.state.postInfo)
axios.post(URL, HEADERS, data)
.then(function (response) {
console.log(response);
console.log(data)
}).catch(function (error) {
console.log(error);
});
}
这是我的后端。我正在使用python将数据发送到MongoDB。
from flask import Flask, Blueprint, jsonify, session
import json, requests, traceback
import pymongo
from flask_cors import CORS, cross_origin
from Authentication.views import Auth
from WallViews.views import Wall
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
CORS(app)
app.secret_key = 'dsfdsfdsgfdgfdkjgrjk4k5j4k3j54'
app.register_blueprint(Auth)
app.register_blueprint(Wall)
if __name__ == "__main__":
app.run(debug=True)
这是我在python中的路线。
@Wall.route('/saveComments', methods=['POST'])
@cross_origin()
def saveComments():
header['Access-Control-Allow-Origin'] = '*'
data = request.data #{'comment':'Hey'}
db = connectToDB()
commentCollection = db.Comments
commentCollection.insert_many(data)
app.config['CORS_HEADERS'] = 'Content-Type'
return jsonify('Saved Data!')