Cannot get XmlHttpRequest to work with CORS -


i made small application gets data weighing scale on rs232, , returns data builtin web server, on url http://localhost:51111/scale1?min=1.5&max=420 . params set config data scale.

now need data in web page, served iis server on central machine. there cors issue here, firefox seems support cors:

var supportscors = (new xmlhttprequest()).withcredentials !== undefined; 

returns true.

using info found on several fora , js books, made js code:

    function httpgetasync() {         var theurl = 'http://localhost:51111/scale1?min=1.5&max=420';         var req = new xmlhttprequest();         req.onreadystatechange = function () {             if (req.readystate == xmlhttprequest.done) {                 $('#value').text('state: ' + req.readystate + ', status: ' + req.status + ', text: ' + req.responsetext);             }         }         req.open("get", theurl, true); // true asynchronous          req.send(null);         return;     } 

the web page has http headers allow cross origin request scripting (cors):

access-control-allow-origin: http://localhost:51111 access-control-allow-methods: get,post 

using fiddler , firefox debugger (f12) can see js indeed sending request local application listening port 51111, on app can see min/max data received correctly, , app responses status 200, , data in body, raw response:

http/1.1 200 ok content-length: 4 server: microsoft-httpapi/2.0 date: tue, 15 aug 2017 14:36:50 gmt  1.15 

looking cool, but:

my problem above js not have body content: req.status 0 0, not 200, , req.responsetext empty string instead of "1.15" .

i tried firefox , chrome.

the http://localhost:51111 server needs configured send access-control-allow-origin response header , other necessary access-control-allow-* response headers. that’s because it’s server frontend js code sending request.

the response cited in question doesn’t show being received response headers, seems must not have http://localhost:51111 server configured send them.

by default browsers won’t allow frontend js code access response cross-origin request—unless server opts-in allowing it. , way servers opt-in allowing cross-origin requests sending access-control-allow-origin response header in responses.

all actual enforcement of cors protocol done browsers. access-control-allow-origin response header servers use communicate browsers; servers use telling browsers origins want browsers expose responses server to.

so that’s why in case http://localhost:51111 server 1 need configure send right access-control-allow-origin response header.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -