json 跨域 $http 请求 AngularJS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22546177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:13:17  来源:igfitidea点击:

Cross-domain $http request AngularJS

jsonangularjshttpcross-domain

提问by Tom

I have simple website I'm building with AngularJS which calls an API for json data.

我有一个简单的网站,我正在使用 AngularJS 构建它,它为 json 数据调用 API。

However I am getting Cross domain origin problem is there anyway around this to allow for cross domain requests?

但是,我遇到了跨域源问题,无论如何,是否允许跨域请求?

Error:

错误:

XMLHttpRequest cannot load http://api.nestoria.co.uk/api?country=uk&pretty=1&action=search_listings&place_name=soho&encoding=json&listing_type=rent. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost' is therefore not allowed access.

XMLHttpRequest 无法加载http://api.nestoria.co.uk/api?country=uk&pretty=1&action=search_listings&place_name=soho&encoding=json&listing_type=rent。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'http:// localhost'。

  searchByPlaceName: function() { 
        var url = baseurl+'country=uk&pretty=1&action=search_listings&place_name=london'+encoding+type;
         return $http.get(url);
    }

回答by Explosion Pills

It seems that api.nestoria.co.ukdoes not allow CORS. It has to set the Access-Control-Allow-Originheader itself -- you have no direct control over that.

似乎api.nestoria.co.uk不允许CORS。它必须设置Access-Control-Allow-Origin标头本身——您无法直接控制它。

However, you can use JSONP. That site allows it via the callbackquery parameter.

但是,您可以使用 JSONP。该站点通过callback查询参数允许它。

$http.jsonp(baseurl+'country=uk&pretty=1&action=search_listings&place_name=london'
    +encoding+type + "&callback=JSON_CALLBACK")

回答by uiwarrior

Install Fiddler. Add a custom rule to it:

安装提琴手。为其添加自定义规则:

static function OnBeforeResponse(oSession: Session)
{
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
}

This would allow you to make cross domain requests from localhost. If the API is HTTPS make sure you enable 'decrypt HTTPS traffic' in fiddler.

这将允许您从本地主机发出跨域请求。如果 API 是 HTTPS,请确保在 fiddler 中启用“解密 HTTPS 流量”。

Reference

参考

-------------------- UPDATE

- - - - - - - - - - 更新

The response you are getting is JSON. Specifying JSONP as datatype would not work. When you do specify JSONP the return should be a function not JSON object.

您得到的响应是 JSON。将 JSONP 指定为数据类型将不起作用。当您指定 JSONP 时,返回应该是一个函数而不是 JSON 对象。

JSONP

JSONP