Home > Mobile >  Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is pre
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is pre

Time:09-24

I'm trying to get informations from a SystemLinkServlet.

So I tried to execute this JavaScript code from a Nintex Forms (Sharepoint) :

var http = new XMLHttpRequest();
var url = 'www.exampleservlet.com';
var params = "anyxml" 

http.open('POST', url, true)

http.setRequestHeader('Content-type', 'application/xml');
http.setRequestHeader('Access-Control-Allow-Origin', '*');

http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
};

http.send(params);

But I still got this error in my console :

Access to XMLHttpRequest at 'www.exampleservlet.com' from origin 'www.exampleorigin.com' 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.

It seems that the header is ignored or maybe I can't set multiple request headers?

It works on Postman.

Update

So It worked with an extension but apparently, I can't set headers with JavaScript code in my Nintex Forms.

I'm trying to find to pass those headers without using an extension.

CodePudding user response:

If you are using PHP, try adding the following code at the beginning of the php file:

If you are using localhost, try this:

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

If you are using external domains such as server, try this:

header("Access-Control-Allow-Origin: http://www.webiste.com");

Also you I suggest you to use this extension:

https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino?hl=en

CodePudding user response:

Postman or other similar tools provide you development environments. In this way, you can ignore and pass CORS rule while sending request and getting response by changing tool settings. But if you sending request via browser(chrome, firefox etc.), browsers always add some preflight controls.

For example, browser send options message to get server side rule before your http request. So that invalid or wrong requests are blocked by browser before processing your http request.

In your case, server side must include your domain information. You can not change this communication rule from client side by adding just "Access-Control-Allow-Origin: *" or "Access-Control-Allow-Origin: http://www.webiste.com" statements.

  • Related