JavaScript - 如何为浏览器GET设置请求标头

Ism*_*ilS 14 javascript browser rest httprequest http-headers

如果我们这样做window.location = "http://MyApi.com/Pdf";,浏览器会对URL进行GET http://MyApi.com/Pdf.但是,如果我们想authentication在执行URL的GET之前设置请求的标头,因为服务器是REST服务器并且它不支持cookie.这该怎么做?

在所有情况下,我都$.ajax用来调用服务,但这次我需要在新窗口中显示响应.响应是PDF文件内容.

提前致谢.

mal*_*lix 9

在更新的浏览器中,您可以使用blob:

<!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>
Run Code Online (Sandbox Code Playgroud)

在IE中,询问用户:

window.navigator.msSaveOrOpenBlob(blob, 'readme.pdf');
Run Code Online (Sandbox Code Playgroud)

PS你可以在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');
});
Run Code Online (Sandbox Code Playgroud)