I'm aware of the whole " preflight request " story... and my server does support options request.
What bothers me is that I tried every single online API testing {Postmamn,reqbin...} and it works just fine but when I use simple axios code or fetch I get the options request with status of 401 Unauthorized!
Localhost env runs on localtunnel & i'm using next.js default server configuration
Added nginx to the server from https://enable-cors.org/server_nginx.html
/example.com/conf/nginx/cors.conf
**Axios code**
var myHeaders = new Headers();
myHeaders.append("Access-Token", "token-here");
var requestOptions = {
method: 'get',
headers: myHeaders,
crossDomain: true,
redirect: 'follow'
};
fetch("https://example.com/x/wp-json/api", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Console error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/xx/wp-json/x/api. (Reason: CORS preflight response did not succeed). Status code: 401.
(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:3000, http://localhost:3000’)
Server has the following headers |
---|
access-control-allow-credentials:true |
access-control-allow-headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type |
access-control-allow-methods: OPTIONS, GET, POST, PUT, PATCH, DELETE |
access-control-allow-origin: https://localtunnel-URL.loca.lt |
content-type: application/json; charset=UTF-8 |