无法设置Access-Control-Allow-Origin请求标头

时间:2016-01-11 20:01:57

标签: ajax xmlhttprequest

我向food2fork api发出AJAX请求,无法通过 No'Access-Control-Allow-Origin'标头出现错误。我已尝试在<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="match_parent" android:layout_width="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="not downloaded" android:id="@+id/text1" android:textSize="30dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/text1" android:layout_marginTop="30dp" android:layout_centerHorizontal="true" android:text="click to download" android:id="@+id/click" /> </RelativeLayout> 设置标题并设置beforeSend,但它无效。

这是我的AJAX电话:

crossDomain: true

我尝试在node express.js中设置请求标头服务器端:

$.ajax({
      type: "GET",
      dataType: 'json',
      url: url,
      crossDomain: true, 
      beforeSend: function(xhr) {
          xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
      },
      success: function(data){
          console.log('in ajax json call');
          console.log(data);
          $('#info').html(JSON.stringify(data));
      }
    });

Cors是一个npm包,它设置了交叉引用权限,但没有帮助我解决问题。

你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:0)

在这种情况下,客户端请求不起作用。我不得不做请求服务器端:

router.post('/test', function(req,res){

var callback = function(response){
 var str = '';

 //another chunk of data has been recieved, so append it to `str`
 response.on('data', function (chunk) {
   str += chunk;
 });

 //the whole response has been recieved
 response.on('end', function () {
   var recipes = JSON.parse(str);
   //do something with recipes
 });
}

var options = {
 host: "food2fork.com",
 path: "/api/search?key=[myKey]&q=" + ingredients
};

http.request(options,callback).end();

});

来自nodejitsu.com

的已使用代码
相关问题