JavaScript - 如何为浏览器 GET 设置请求标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8505280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - How to set request header for a browser GET
提问by IsmailS
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?
如果我们这样做window.location = "http://MyApi.com/Pdf";
,浏览器会执行 URL 的 GET http://MyApi.com/Pdf
。但是如果我们想authentication
在对 URL 进行 GET 之前设置请求的标头,因为服务器是 REST 服务器并且它不支持 cookie。这该怎么做?
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.
在所有情况下,我都使用$.ajax
调用服务,但这次我需要在新窗口中显示响应。响应是一个PDF文件内容。
Thanks in advance.
提前致谢。
采纳答案by malix
In more recent browsers, you might be able to use blobs:
在更新的浏览器中,您或许可以使用 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>
In IE, ask the user:
在 IE 中,询问用户:
window.navigator.msSaveOrOpenBlob(blob, 'readme.pdf');
P.S. You can test the backend in Node:
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');
});
回答by Saurabh Kumar
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
https://developer.mozilla.org/en/docs/Setting_HTTP_request_headers
回答by Wumms
If you don't care about hiding or obfuscating the user credentials then just use plain GET authentification:
use http://username:[email protected]/
instead of http://MyApi.com/
如果您不关心隐藏或混淆用户凭据,则只需使用普通的 GET 身份验证:使用http://username:[email protected]/
而不是http://MyApi.com/
回答by Leon
Does it have to be a GET?
它必须是 GET 吗?
The reason I am asking is that you could just have a POST form (to a target="_BLANK") that posts whatever but shows an embedded file in a new window. Of course this wouldn't solve the issue with your custom headers, but then since you can also POST using jquery.ajax - which does allow you to set your own headers - you'd have the best of both worlds.
我问的原因是你可以有一个 POST 表单(到目标 =“_BLANK”),它可以发布任何内容,但在新窗口中显示嵌入的文件。当然,这不会解决您的自定义标头的问题,但是由于您也可以使用 jquery.ajax 进行 POST - 这确实允许您设置自己的标头 - 您将拥有两全其美的优势。
Here's a jQuery pluginthat creates such a form dynamically in order to download whichever file. You could use this as a reference...
这是一个jQuery 插件,它动态创建这样的表单以下载任何文件。你可以把它作为参考...
Hope this helps
希望这可以帮助
回答by Pieter
You should configure $.ajax
using beforeSend
. Below an example, but of course I don't know if the exact setup will work for you without any code to look at.
您应该$.ajax
使用beforeSend
. 下面是一个示例,但当然我不知道确切的设置是否适合您,而无需查看任何代码。
$.ajax( {
url : '/model/user.json',
dataType : 'json',
'beforeSend' : function(xhr) {
var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
var base64 = Crypto.util.bytesToBase64(bytes);
xhr.setRequestHeader("Authorization", "Basic " + base64);
},
error : function(xhr, ajaxOptions, thrownError) {
reset();
onError('Invalid username or password. Please try again.');
$('#loginform #user_login').focus();
},
success : function(model) {
cookies();
...
}
});
For this to work you need crypto-js.
为此,您需要crypto-js。