Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How to set request header for a browser GET

If we do window.location = "http://MyApi.com/Pdf";, browser does a GET of the URL http://MyApi.com/Pdf. But if we want to set authentication header of the request before doing GET of the URL because the server is a REST server and it doesn't support cookies. How to do this?

In all of the cases, I'm using $.ajax to call service but this time I need to show the response in a new window. Response is a PDF file content.

Thanks in advance.

like image 278
IsmailS Avatar asked Dec 14 '11 13:12

IsmailS


People also ask

How do I get HTTP request header in browser?

In Chrome, visit a URL(such as https://www.google.com ), right click, select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.

Can HTTP GET have headers?

Yes, you can send any HTTP headers with your GET request. For example, you can send user authentication data in the Authorization header, send browser cookies in the Cookie header, or even send some additional details about your request in custom headers like X-Powered-By or X-User-IP.

How do I add a custom header to all requests?

Under Custom request headers, click Add header. Enter the Header name and Header value for the custom request header. Enter any additional custom request headers. Click Save.


2 Answers

In more recent browsers, you might be able to use blobs:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="tryit();">PDF</button>
<script>
    function tryit() {
        var win = window.open('_blank');
        downloadFile('/pdf', function(blob) {
            var url = URL.createObjectURL(blob);
            win.location = url;
        });
    }
    function downloadFile(url, success) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
        xhr.responseType = "blob";
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (success) success(xhr.response);
            }
        };
        xhr.send(null);
    }

</script>
</body>
</html>

In IE, ask the user:

window.navigator.msSaveOrOpenBlob(blob, 'readme.pdf');

P.S. You can test the backend in Node:

router.get('/pdf', function(req, res) {
  if(req.headers.authorization !== 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=') return res.status(403).send('Not allowed');
  res.sendFile(path.join(__dirname, 'public', 'render.pdf'));
});
router.get('/', function(req, res) {
  res.render('index');
});
like image 65
malix Avatar answered Sep 19 '22 16:09

malix


I think this is what you are looking for... Or correct me if i am wrong.

https://developer.mozilla.org/en/docs/Setting_HTTP_request_headers

like image 26
Saurabh Kumar Avatar answered Sep 20 '22 16:09

Saurabh Kumar