简体   繁体   中英

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:

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.

You can use JSONP in AngularJS.

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

Documented here .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM