Flask POST请求中没有'Access-Control-Allow-Origin'标头“错误[CORS]

时间:2016-05-18 01:03:01

标签: flask cors flask-cors

我收到以下CORS错误,从角应用程序向烧瓶服务器发出POST请求:

from flask import Flask, request from flask.ext.cors import CORS app = Flask(__name__) cors = CORS(app) @app.route('/testPost', methods=['POST']) def testPost(): phone = request.values.get('phone') return phone if __name__ == '__main__': app.run(debug=True)

Flask服务器:

HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Allow: POST, OPTIONS
Access-Control-Allow-Origin: http://localhost:7000
Access-Control-Allow-Headers: accept, content-type
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Content-Length: 0
Server: Werkzeug/0.11.3 Python/2.7.11
Date: Wed, 18 May 2016 00:58:10 GMT

我尝试过不同响应标头的组合而没有运气。飞行前的OPTIONS请求使用以下标题返回200 ok

响应:

OPTIONS /testPost HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Cache-Control: max-age=0
Access-Control-Request-Method: POST
Origin: http://localhost:7000
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://localhost:7000/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

请求:

if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
        {
            sentence = sentence.substring(1, sentence.length()-1);
            return isPalindrome();
        }

1 个答案:

答案 0 :(得分:0)

错误发生在我的testPost()方法的返回类型中。该方法需要返回json响应。

from flask import Flask, request
from flask.ext.cors import CORS
app = Flask(__name__)
cors = CORS(app)

@app.route('/testPost', methods=['POST'])
def testPost():
  phone = request.json['phone']
  return phone

if __name__ == '__main__':
  app.run(debug=True)