0

I have this get request to a server. This site is hosted on a dev server, but I want to point this get request to a production server.

var requestList = new XMLHttpRequest();  

requestList.onreadystatechange = function() {  
    if (requestList.readyState==4&&requestList.status==200) {  
        display(JSON.parse(requestList.responseText));  
    }  
};  
requestList.open('GET','<link/to/php/server>',true);  
requestList.withCredentials = true;  

I'm getting a cors error. But, I can run this request from something like PowerShell and it works with the following code:

$url = "<link/to/php/server>"
$wc = New-Object System.Net.WebClient
$wc.UseDefaultCredentials = $true
$response = $wc.DownloadString($url)
$df = ConvertFrom-Json $([String]::new($response))

The PowerShell code just uses windows credentials. Since the PowerShell code works, I know I should be able to query the production server. But how to do it with JavaScript XMLHttpRequest?

Frank
  • 952
  • 1
  • 9
  • 23
  • 1
    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – epascarello Apr 26 '22 at 12:58
  • 1
    Browers apply the [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy), because it makes sense for browsers to do that. PowerShell does not, because it doesn't make sense for it to. – T.J. Crowder Apr 26 '22 at 13:01
  • 1
    Powershell, etc, do not expect nor pay attention to CORS headers, so it will "work", however the problem is that your browser's security won't allow it without the correct response headers from your server. – James Apr 26 '22 at 13:02
  • @T.J.Crowder Are you saying the answer to my question is that there is no solution? – Frank Apr 26 '22 at 14:07
  • @Frank - No, I'm saying the answer to your question is provided by the answers [here](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i). The production server would need to reply with the necessary CORS headers to allow calls to it from a page on your development system. – T.J. Crowder Apr 26 '22 at 14:13
  • Or you use a proxy. Many dev environments start the frontend in a small dev server with dev proxy, e.g. you can use the webpack dev server. Later you could host the frontend and backend on the same origin. – jabaa Apr 26 '22 at 14:18
  • Unfortunately I can't implement any of these solutions without huge effort because I can't access server due to bureaucratic issues here. I think I will use PowerShell to run the get request and save the output as json file onto the webserver file system and read that with fetch in javascript. It sucks, but it is 1000000 times faster than suggested sigh. If anyone knows a better work-around, pleaseeeee let me know – Frank Apr 26 '22 at 14:45
  • You can use a browser extension to deactivate same-origin policy. – jabaa Apr 26 '22 at 14:51

0 Answers0