S
S
Sergei Gurdjiyan2019-03-03 10:34:43
JavaScript
Sergei Gurdjiyan, 2019-03-03 10:34:43

How to solve CORS issue when working with Wordpress API?

Stack: Vue, Nuxt, Wordpress API.
When making a request to
https://site/wp-json/wp/v2/pages/2
, everything works, but when specifying the language, an error occurs

Access to XMLHttpRequest at ' https://site/wp-json/wp/v2/pages/2?lang=en ' from origin ' localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin ' header is present on the requested resource.

I tried to specify ' Access-Control-Allow-Origin': '*'both in functions.php and in axios config. There is no result.
The problem arises when
- The project is local, and WP is hosted
- The project is hosted, and WP is on a subdomain.
How to solve the problem?
Is it possible to somehow configure so that cors does not throw an error exactly when requesting from a specific url?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
G
grinat, 2019-03-07
@mrKorg

Specifying Access-Control-Allow-Origin in php is not enough, you also need to enable options support. js has nothing to do with it at all, you can’t configure anything there, only the server allows you to make a cross-request.
see https://developer.mozilla.org/ru/docs/Web/HTTP/CORS
Oh yes, you can still configure everything in the http server (in nginx or in apache):
https://enable-cors.org/server_nginx. html
https://benjaminhorn.io/code/setting-cors-cross-or...
in this case there is no need to pull php

O
Orkhan Hasanli, 2019-03-03
@azerphoenix

If my memory serves me, then I came across this when working on the Java Wordpress REST API. This plugin helped me - https://github.com/WP-API/Basic-Auth
Although, your situation is different - https://stackoverflow.com/questions/53129894/acces...

B
Boris Cherepanov, 2019-06-22
@xakplant

In some cases, it is not sufficient to set the Access-Control-Allow-Origin header to "*". For some situations, you need to specify the exact address where requests can be sent, for example, if you are trying to authorize on the server, betray the headers, or you need to read the response headers.
I wrote several examples in the article. Might be useful to someone

V
Vladimir Dementiev, 2019-03-03
@SayMAN83

Ran into this in c# and angular. In general, as I found out, cross-domain connections on js are disabled by default due to security. Therefore, you need to configure cors. Just enable Access-Control-Allow-Origin support.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question