我想从一个区块链API中获取数据..
在控制器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');
}
}
in 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.
您误解了CORS的工作原理。您已将CORS标头添加到您自己的代码中,而标头需要从Blockchain.info输出。
某些区块链API调用可以附加&cors=true
以获取CORS标题,但不能将其提供此特定端点。
解决方案是通过自己的服务器端代理您的API调用。在PHP代码中创建一个将调用区块链API的路由。服务器到服务器请求将不受CORS的约束。通过Ajax致电您的PHP路线。