No 'Access-Control-Allow-Origin' header is present on the requested resource

In Postman this Post request runs just perfect:
var settings = {
ā€œurlā€: ā€œhttps://webservicesp.anaf.ro/AsynchWebService/api/v5/ws/tvaā€,
ā€œmethodā€: ā€œPOSTā€,
ā€œtimeoutā€: 0,
ā€œheadersā€: {
ā€œContent-Typeā€: ā€œapplication/jsonā€
},
ā€œdataā€: JSON.stringify([{ā€œcuiā€:2864518,ā€œdataā€:ā€œ2021-03-29ā€}]),
};

$.ajax(settings).done(function (response) {
console.log(response);
});

But when I try to run it from from our WordPress web-store, from a .js file when leaving a field:
$(ā€™#billing_cuiā€™).blur(
function(){ā€¦

I get:
Access to XMLHttpRequest at ā€˜https://webservicesp.anaf.ro/AsynchWebService/api/v5/ws/tvaā€™ from origin ā€˜https://ā€¦ā€™ has been blocked by CORS policy: Response to preflight request doesnā€™t pass access control check: No ā€˜Access-Control-Allow-Originā€™ header is present on the requested resource.
webservicesp.anaf.ro/AsynchWebService/api/v5/ws/tva:1 Failed to load resource: net::ERR_FAILED

Hi @Valdinia, Welcome to Community!

It seems the endpoint which you are trying to use has CORS policy enabled. You need to pass headers like the one mentioned ā€œAccess-Control-Allow-Originā€ in your error message.

Generally postman includes these headers by default. To verify this you can check for hidden or auto populated headers under header tab in postman else you can also find in postman console what all headers were sent in the request payload.

If policy is there you may need to pass extra headers to align with CORS policy in your JS script from wordpress.

Hope this helps :slightly_smiling_face:

Thank you for your answer!

Have you found a solution yet? i`m struggling with the same exact problemā€¦

The error you get is due to the CORS standard, which sets some restrictions on how JavaScript can perform ajax requests.

The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server.

Postman does not implement the CORS restrictions, which is why you donā€™t see the same error when making the same call from Postman.

Why doesnā€™t Postman implement CORS? CORS defines the restrictions relative to the origin (URL domain) of the page which initiates the request. But in Postman the requests doesnā€™t originate from a page with an URL so CORS does not apply.

2 Likes

When using the Postman website to make the requests, are we still using the Postman app instead of the brwoser, when making the API request to the API server?

I couldnā€™t make this work either.
My server was definitely running and I could make WS connections on localhost:8080 using a test index.html page using the JS websocket API.

I gave up and installed the WebSocket King Chrome extension and it worked out of the box, no issues.

Just FYI.
Thanks,
Murray