Access-Control-Allow-Origin – Error when trying to access JSON from WordPress installation

I try to access my blog using the “old” Json-Api from JavaScript (AngularJS)

Now I receive the following error:

Read More

XMLHttpRequest cannot load
http://example.com/?json=get_category_index. No
‘Access-Control-Allow-Origin’ header is present on the requested
resource. Origin ‘http://localhost:63342‘ is therefore not allowed
access.

Looks like a simple thing. But even after I tried the following:

Add these lines into the .htaccess:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Add the following line to the themes’ header.php and to json-api.php:

<? header("Access-Control-Allow-Origin: *"); ?>

I still get this error.

Related posts

3 comments

  1. You can use JSONP in AngularJS.

    JSONP is used to request data from a server in a different domain.

    Documented here.

  2. Ok. Solved it. Was a bit tricky:

    I had to change “><? xxx ?>” to “<?php xxx ?>

    The “<?” – part was not rendered as server-code but was output like normal html.

  3. The remote server that you’re trying to access (JSON) is the one that should allow Access-Control-Allow-Origin, not your WordPress host.

    If they’re in the same server, then it could be that you forgot to set relative URLs, so when trying from localhost you won’t be able to access your web host.

Comments are closed.