简体   繁体   中英

Adding Request Headers on JavaScript

I am preparing a JavaScript. Below is the code for the same:

 <html> <head> <body> <script> var getJSON = function(url, successHandler, errorHandler) { var xhr = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhr.open('get', url, true); xhr.onreadystatechange = function() { var status; var data; if (xhr.readyState == 4) { status = xhr.status; if (status == 200) { data = JSON.parse(xhr.responseText); successHandler && successHandler(data); } else { errorHandler && errorHandler(status); } } }; xhr.send(); }; getJSON('https://example.com/lol.json', function(data) { alert('Your Token is: ' + data.token); }, function(status) { alert('Something went wrong.'); }); </script> </body> </head> </html> 

So, this snipped is without "access-control-allow-origin" and I am running this locally, so I have used file:/// by disabling the security features of chrome.

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

I need to run this one without disabling the security features means by adding the request headers like:

res.setHeader('Access-Control-Allow-Origin', "http://"+req.headers.host+':8000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();

Actually, I am not too good in JavaScript and messing with the same since morning. Can Any one help me regarding this that how I merge these request headers in the snippet.

You will have to update the startup of the chrome by using the following :

-disable-web-security -user-data-dir

You can add this to response header in your server side:

file://

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM