jquery – 如何在烧瓶和heroku中启用CORS

前端之家收集整理的这篇文章主要介绍了jquery – 如何在烧瓶和heroku中启用CORS前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用 jquery做一个十字架请求,但是它一直被拒绝与消息

XMLHttpRequest cannot load http://… No ‘Access-Control-Allow-Origin’
header is present on the requested resource. Origin … is therefore
not allowed access.

我正在使用烧瓶,英雄和jquery

客户端代码如下所示:

  1. $(document).ready(function() {
  2. $('#submit_contact').click(function(e){
  3. e.preventDefault();
  4. $.ajax({
  5. type: 'POST',url: 'http://...',// data: [
  6. // { name: "name",value: $('name').val()},// { name: "email",value: $('email').val() },// { name: "phone",value: $('phone').val()},// { name: "description",value: $('desc').val()}
  7. //
  8. // ],data:"name=3&email=3&phone=3&description=3",crossDomain:true,success: function(msg) {
  9. alert(msg);
  10. }
  11. });
  12. });
  13. });

在英雄方面我正在使用烧瓶,就像这样

  1. from flask import Flask,request
  2. from flask.ext.mandrill import Mandrill
  3. try:
  4. from flask.ext.cors import CORS # The typical way to import flask-cors
  5. except ImportError:
  6. # Path hack allows examples to be run without installation.
  7. import os
  8. parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  9. os.sys.path.insert(0,parentdir)
  10.  
  11. from flask.ext.cors import CORS
  12. app = Flask(__name__)
  13.  
  14. app.config['MANDRILL_API_KEY'] = '...'
  15. app.config['MANDRILL_DEFAULT_FROM']= '...'
  16. app.config['QOLD_SUPPORT_EMAIL']='...'
  17. app.config['CORS_HEADERS'] = 'Content-Type'
  18.  
  19. mandrill = Mandrill(app)
  20. cors = CORS(app)
  21.  
  22. @app.route('/email/',methods=['POST'])
  23. def hello_world():
  24. name=request.form['name']
  25. email=request.form['email']
  26. phone=request.form['phone']
  27. description=request.form['description']
  28.  
  29. mandrill.send_email(
  30. from_email=email,from_name=name,to=[{'email': app.config['QOLD_SUPPORT_EMAIL']}],text="Phone="+phone+"\n\n"+description
  31. )
  32.  
  33. return '200 OK'
  34.  
  35. if __name__ == '__main__':
  36. app.run()

解决方法

当我部署到Heroku时,这是对我有用的.

http://flask-cors.readthedocs.org/en/latest/

$pip install -U flask-cors

  1. from flask import Flask
  2. from flask.ext.cors import CORS,cross_origin
  3. app = Flask(__name__)
  4. cors = CORS(app)
  5. app.config['CORS_HEADERS'] = 'Content-Type'
  6.  
  7. @app.route("/")
  8. @cross_origin()
  9. def helloWorld():
  10. return "Hello,cross-origin-world!"

猜你在找的jQuery相关文章