如何从一个跨域API获取数据 [英] How can I get data from a Cross domain API

查看:387
本文介绍了如何从一个跨域API获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从不同域中的API获取数据,但我得到这个错误:

I'm trying to get data from an API in a different domain but I get this error:

XMLHtt prequest无法加载 https://www.bitstamp.net/api/ticker/ 。没有
  访问控制允许来源标头present的要求
  资源。因此,原产地的'localhost'是不允许的
  访问。

XMLHttpRequest cannot load https://www.bitstamp.net/api/ticker/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost' is therefore not allowed access.

我试图在头添加此,但它仍然无法正常工作:

I tried to add this in the header but it still doesn't work:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    Access-Control-Allow-Origin: https://www.bitstamp.net
</head>
<body>
<script src="Index.js"></script>
</body>
</html>

这是我的JavaScript:

This is my JavaScript:

var ticker = "https://www.bitstamp.net/api/ticker/";
$.ajax({
    dataType: "json",
    url: ticker,
    type: "POST",
    crossDomain: true,
    scriptCharset: "utf-8"
});

我不能使用 JSONP ,因为该网站不支持这一点。
我怎样才能收到不同的域上从JSON API的数据?
我想是 JavaScript或C#这样做

I can not use JSONP because the website doesn't support this. How can I receive the data from the API with JSON on a different domain? I would like to do this with JavaScript or C#.

推荐答案

添加类到你的项目,并用它标记您的控制器

add class to you project and mark your Controllers with it

public class AllowCrossSiteAttribute : ActionFilterAttribute {

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       if (actionExecutedContext.Response != null)
         actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
          base.OnActionExecuted(actionExecutedContext);
        }
    }
}

然后控制器添加到控制器的方法选择,因为第一次调用将选项来得到,如果十字allowd

then in Controller add to controller method option because first call will be to options to get if CROSS is allowd

[System.Web.Http.AllowAnonymous]
public HttpResponseMessage Options()
{
    return new HttpResponseMessage(HttpStatusCode.OK);
}

(请不,在这里你允许所有域名,但你可以用你的域列表取代*)

(Please not that here you allow all domain but you can replace "*" with list of your domains)

或者使用Web配置(但它会为所有控制器)

Or using web config (But it will be for all controllers)

<system.webServer>
    <httpProtocol>
        <customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

选件asp.net web表单可能是

Option for asp.net web forms could be

Response.AppendHeader("Access-Control-Allow-Origin", "*");

这篇关于如何从一个跨域API获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆