为什么,Accessign-Control-Allow-Origin在Codeigniter Rest-Server中不起作用

时间:2017-05-30 09:52:53

标签: javascript ajax codeigniter cors

我想从BLOCKCHAIN API中获取数据....

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

控制器Cart.php中的

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    If Worksheets("sheet1").AutoFilterMode = True Then
    MsgBox "Filters not allowed, remove filters ", vbExclamation, "Warning!"
    Cancel = True

   Exit Sub
   End If
   End Sub

在Asyc.js

<?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');
    }
}

我收到了错误

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

1 个答案:

答案 0 :(得分:2)

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

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

解决方案是通过您自己的服务器端代理您的api呼叫。在您的PHP代码中创建一个将调用区块链api的路由。服务器到服务器请求不受CORS约束。通过ajax调用你的php路由。