2017-05-30 89 views
2

我想从BLOCKCHAIN API中获取数据....为什么Access-Control-Allow-Origin在Codeigniter Rest-Server中不起作用

但是我遇到了一个小问题,想在使用'AJAX GET REQUEST'和dddddd taraaaaaaa后,使用'CORS HEADER'方法访问API和无意中的API BLOCKCHAIN,我得到错误:)。

在控制器Cart.php

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 

class Cart extends CI_Controller { 

    /** 
    * Index Page for this controller. 
    * 
    * Maps to the following URL 
    *  http://example.com/index.php/welcome 
    * - or - 
    *  http://example.com/index.php/welcome/index 
    * - or - 
    * Since this controller is set as the default controller in 
    * config/routes.php, it's displayed at http://example.com/ 
    * 
    * So any other public methods not prefixed with an underscore will 
    * map to /index.php/welcome/<method_name> 
    * @see https://codeigniter.com/user_guide/general/urls.html 
    */ 
    public function __construct() 
    { 
     parent::__construct(); 
     header("Access-Control-Allow-Methods: GET, OPTIONS"); 
     header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding"); 
     if ("OPTIONS" === $_SERVER['REQUEST_METHOD']) { 
     die(); 
     } 
    } 
    public function index() 
    { 
     $this->load->view('cart_view'); 
    } 
} 

在Asyc.js

$.getJSON("https://blockchain.info/rawaddr/1N1WJYDUgaBrk9eUfawSYurs9ZtKcVVfTE", function(data) { 
    console.log(data); 
}); 

我得到错误

XMLHttpRequest cannot load https://blockchain.info/rawaddr/1N1WJYDUgaBrk9eUfawSYurs9ZtKcVVfTE. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 
+0

'Controller Cart.php'是生成'https:// blockchain.info/rawaddr/1N1WJYDUgaBrk9eUfawSYurs9ZtKcVVfTE'或'http:// localhost'的文件吗? – Quentin

回答

2

你误解CORS是如何工作的。您已将CORS头添加到您自己的代码中,而头需要从blockchain.info输出,这当然是您无权访问的。

某些区块链API调用可以附加&cors=true以获取CORS头,但不是此特定端点。

解决方案是通过您自己的服务器端代理您的API调用。在您的PHP代码中创建一个路由,它将调用区块链API。服务器到服务器的请求不会受到CORS的影响。通过ajax调用你的php路由。

+0

你能举一个简单的例子吗? – Firmansyah

+0

在你的控制器中创建一个新的方法,它会执行'echo file_get_contents('https://blockchain.info/rawaddr/1N1WJYDUgaBrk9eUfawSYurs9ZtKcVVfTE')'',并从你的javascript载入这个页面,而不是加载blockchain.info – Antony

相关问题