即使REST服务器设置标头,Access-Control-Allow-Origin也会出错

时间:2014-06-28 07:43:50

标签: javascript python ajax flask cors

我正在尝试了解REST服务器并托管烧瓶服务器。

在服务器URL上运行curl我得到:

HTTP/1.1 200 OK
Access-Control-Allow-Methods: POST, OPTIONS, GET, HEAD
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 21600
Content-Type: text/html; charset=utf-8
Date: Sat, 28 Jun 2014 07:08:41 GMT
Server: gunicorn/19.0.0
Content-Length: 36
Connection: keep-alive

但是当我尝试从另一个网址访问数据时,我得到:

  

XMLHttpRequest无法加载 - 服务器网址 - 。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。原因 - 页面网址 - 因此不允许访问。

到目前为止,我尝试过以下代码来获取数据:

  var formData = new FormData();
  formData.append("name",username );
  formData.append("id", userid);

  var request = new XMLHttpRequest();
  request.open("POST", "my-server-url");
  request.send(formData);
  console.log("Running Create user")
  console.log("Status: "+request.status);
  console.log("error: "+request.error);
  console.log("responseText: "+request.responseText);

返回

Running Create user
Status: 0
error: undefined
responseText: 

我尝试过使用ajax和jquery,它也会因上述错误而失败

  $.ajax({  
            url:'--server url--',  
            type:'POST',
            data :  mydata,      
            dataType: 'JSON',
            success: function(data) { 
                  console.log(data)   
            }  
        }); 

  $.ajax({  
                url:'--server url--',  
                type:'POST',
                data :  mydata,      
                dataType: 'JSONP',
                async: false,
                success: function(data) { 
                      console.log(data)   
                }  
            }); 

我在python代码中使用crossdomain decorator snippet

我的服务器路由处理示例:

@app.route("/",  methods=['POST', 'GET', 'OPTIONS'])
@crossdomain(origin='*')
def create():
    if request.method == 'POST':
        name = request.form['name']
        id = request.form['id']
        #duplicate = collection.find_one({'name': name, 'token': token})
        duplicate = collection.find_one({'id': id})
        if not duplicate:
            data = {'name': name,
                    'id': id}
            collection.insert(data, safe=True)
            response= make_response({'status': 'created'}, 201)
            response.headers['Access-Control-Allow-Origin'] = "*"
            return response 
        else:
            response= make_response({'status': 'already exists'}, 302)
            response.headers['Access-Control-Allow-Origin'] = "*"
            return response

1 个答案:

答案 0 :(得分:0)

我终于设法解决了这个问题,我对ajax代码进行了以下更改

var formData = new FormData();
formData.append("id", userid); 
$.ajax({
            url: '--server--',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(data){
              //do something with data
              console.log(data)
            },
            error: function(e) {
                    //handle error
                    console.log(e)
                  }


          })

我也必须在服务器上进行此更改:

@app.route("/",  methods=['POST', 'GET', 'OPTIONS'])
@crossdomain(origin='*')
def create():
    if request.method == 'POST':
        name = request.form['name']
        id = request.form['id']
        #duplicate = collection.find_one({'name': name, 'token': token})
        duplicate = collection.find_one({'id': id})
        if not duplicate:
            data = {'name': name,
                    'id': id}
            collection.insert(data, safe=True)
            return jsonify({'status': 'created'}), 201
        else:
            return jsonify({'status': 'already exits'}), 302