首页 > 解决方案 > 如何将 curl 转换为 ajax?

问题描述

并尝试获取 API 密钥。该网站给了我一些卷曲代码。好吧,因为我是韩国人,不确定我是否理解了描述。无论如何,

    curl --insecure -X POST 
   --header "Content-Type: application/x-www-form-urlencoded" 
   --header "Accept: application/json" 
   --data-urlencode "grant_type=urn:grant-type:apikey"
   --data-urlencode "apikey=$API_KEY" "https://iam~~"

这是代码,我想知道在 ajax 调用代码上放置“--data-urlencode”部分的位置。

    function to_ajax(){
    $.getJSON("http://localhost~~/",
    function(data){
        $.ajax({
            dataType: 'application/json', 
            data : {"grant_type":"urn:grant-type:apikey"
                    ,"apikey=$API_KEY":"https://iam~~"},
            headers: {"Content-Type" : "application/x-www-form-urlencoded" , 
            "Accept": "application/json" } ,
            success: function(msg) {
              console.log(msg);
            }
        });

    })
}

这是我到达的地方......耻辱......当我运行它时,我得到了CORS错误。IBM 解释说,API Gateway 可以运行 API CORS 操作来处理 API 的跨域资源共享 (CORS) 请求。

默认情况下,API 禁用 CORS,在这种情况下,API 网关将所有 CORS 请求传递到后端进行处理。当预检请求被传递到后端时,必须为每个可以成为请求目标的路径定义一个 OPTIONS 操作。否则,对该路径的预检请求可能会导致错误。

所以这意味着他们允许所有访问权限,对吗?

标签: javascriptajaxcurl

解决方案


对于 Ajax,3 个选项,我还添加了 ASP 答案,因为它出现在我的 ASP 搜索标签中!

  1. 将此添加到您的 Ajax 调用中的标题中。它仅限于一个站点,您可以使用 a*使其允许所有站点(不推荐)

headers: { 'Access-Control-Allow-Origin': 'http://The web site you are specially allowing to access' },// 或使用 *

   function to_ajax(){
    $.getJSON("http://localhost~~/",
    function(data){
        $.ajax({
            dataType: 'application/json', 
            data : {"grant_type":"urn:grant-type:apikey"
                    ,"apikey=$API_KEY":"https://iam~~"},

            headers: { 'Access-Control-Allow-Origin': 'http://TCUrl stack overflow' }, //only a specific site
            headers: {'Access-Control-Allow-Origin': '*'}, //or allow everybody  

            headers: {"Content-Type" : "application/x-www-form-urlencoded" , 
            "Accept": "application/json" } ,
            success: function(msg) {
              console.log(msg);
            }
        });

    })
  1. 或与Jsonp

    // 如果其他服务器允许 JSONP $.ajax({ type: 'POST', crossDomain: true, dataType: 'jsonp', url: '', success: function(jsondata){

    } })

  2. 您可以使用Ajax-cross-origin 一个 jQuery 插件。使用此插件,您可以使用jQuery.ajax()跨域。它使用谷歌服务来实现这一点:

AJAX Cross Origin 插件使用 Google Apps 脚本作为未实现 jSONP 的代理 jSON getter。当您将 crossOrigin 选项设置为 true 时,插件会将原始 url 替换为 Google Apps 脚本地址并将其作为编码的 url 参数发送。Google Apps 脚本使用 Google 服务器资源来获取远程数据,并将其作为 JSONP 返回给客户端。

易于使用以下插件:

    $.ajax({
        crossOrigin: true,
        url: url,
        success: function(data) {
            console.log(data);
        }
    });

你可以在这里阅读更多: http ://www.ajax-cross-origin.com/

  1. 对于 ASP Web 应用程序,web.config请在您的内部添加以下 protocall选项以允许 CORS 调用。

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>


推荐阅读