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.
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.
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.
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.
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');
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With