将 JavaScript 中的 HTTP 标头添加到图像请求中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21841426/
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
Add HTTP Header in JavaScript to requests for images
提问by bernhardh
I have a JS/HTML5 Project based on angularjs where I protect the api with an authorization token set in the http header. Now I also want to protect the access to images from the server.
我有一个基于 angularjs 的 JS/HTML5 项目,我使用在 http 标头中设置的授权令牌来保护 api。现在我还想保护从服务器对图像的访问。
I know how to do it on the server side, but how can I add HTTP Headers to image requests in angular or javascript? For api request we have already added it to the services ($ressource) and it works.
我知道如何在服务器端执行此操作,但是如何将 HTTP 标头添加到 angular 或 javascript 中的图像请求?对于 api 请求,我们已经将它添加到服务 ($ressource) 中并且它可以工作。
回答by Ben Lesh
In Angular 1.2.X
在 Angular 1.2.X 中
There are more than a few ways to do this. In Angular 1.2, I recommend using an http interceptorto "scrub" outgoing requests and add headers.
有很多方法可以做到这一点。在 Angular 1.2 中,我建议使用http 拦截器来“清理”传出请求并添加标头。
// An interceptor is just a service.
app.factory('myInterceptor', function($q) {
return {
// intercept the requests on the way out.
request: function(config) {
var myDomain = "http://whatever.com";
// (optional) if the request is heading to your target domain,
// THEN add your header, otherwise leave it alone.
if(config.url.indexOf(myDomain) !== -1) {
// add the Authorization header (or custom header) here
config.headers.Authorization = "Token 12309123019238";
}
return config;
}
}
});
app.config(function($httpProvider) {
// wire up the interceptor by name in configuration
$httpProvider.interceptors.push('myInterceptor');
});
In Angular 1.0.X
在 Angular 1.0.X 中
If you're using Angular 1.0.X, you'll need to set the headers more globally in the common headers... $http.defaults.headers.common.Authentication
如果您使用的是 Angular 1.0.X,则需要在公共标头中更全局地设置标头... $http.defaults.headers.common.Authentication
EDIT: For things coming from
编辑:对于来自
For this you'll need to create a directive, and it's probably going to get weird.
为此,您需要创建一个指令,它可能会变得很奇怪。
You'll need to:
你需要:
- Create a directive that is either on your
<img/>
tag, or creates it. - Have that directive use
$http
service to request the image (thus leveraging the above http interceptor). For this you're going to have to examine the extension and set the proper content-type header, something like:$http({ url: 'images/foo.jpg', headers: { 'content-type': 'image/jpeg' }).then(...)
- When you get the response, you'll have to take the raw base64 data and set the
src
attribute of your image element to a data src like so:<img src="data:image/jpeg;base64,9hsjadf9ha9s8dfh...asdfasfd"/>
.
- 创建一个位于您的
<img/>
标签上或创建它的指令。 - 让该指令使用
$http
服务来请求图像(从而利用上述 http 拦截器)。为此,您将不得不检查扩展并设置正确的内容类型标头,例如:$http({ url: 'images/foo.jpg', headers: { 'content-type': 'image/jpeg' }).then(...)
- 当你得到的回应,你就必须采取原始的base64数据和设置的
src
图像元素的属性数据SRC像这样:<img src="data:image/jpeg;base64,9hsjadf9ha9s8dfh...asdfasfd"/>
。
... so that'll get crazy.
......所以这会变得疯狂。
If you can make it so your server doesn't secure the images you're better off.
如果你能做到这一点,你的服务器就不会保护你的图像。
回答by Anthony O.
As said hereyou can use angular-img-http-src(bower install --save angular-img-http-src
if you use Bower).
正如这里所说,您可以使用angular-img-http-src(bower install --save angular-img-http-src
如果您使用Bower)。
If you look at the code, it uses URL.createObjectURL
and URL.revokeObjectURL
which are still drafton 19 April 2016. So look if your browser supports it.
如果你看一下代码,它使用了URL.createObjectURL
和URL.revokeObjectURL
其仍然起草于2016年4月19日因此,如果您的浏览器支持它的样子。
In order to use it, declare 'angular.img'
as a dependency to your app module (angular.module('myapp', [..., 'angular.img'])
), and then in your HTML you can use http-src
attribute for <img>
tag.
为了使用它,将其声明'angular.img'
为对您的应用程序模块 ( angular.module('myapp', [..., 'angular.img'])
)的依赖项,然后在您的 HTML 中您可以使用标签的http-src
属性<img>
。
For example: <img http-src="{{myDynamicImageUrl}}">
例如: <img http-src="{{myDynamicImageUrl}}">
Of course, this implies that you have declared an interceptorusing $httpProvider.interceptors.push
to add your custom header or that you've set statically your header for every requests using $http.defaults.headers.common.MyHeader = 'some value';
当然,这意味着您已经声明了一个拦截器,$httpProvider.interceptors.push
用于添加自定义标头,或者您已经为每个请求静态设置了标头$http.defaults.headers.common.MyHeader = 'some value';
回答by mgoetzke
we have the same issue and solve it using a custom ng-src directive ..
我们有同样的问题并使用自定义 ng-src 指令解决它..
basically a secure-src directive which does exactly what ng-src does (its a copy basically) BUT it extends the url with a query parameter which includes the local authentication header.
基本上是一个安全 src 指令,它与 ng-src 完全一样(它基本上是一个副本),但它使用包含本地身份验证标头的查询参数扩展了 url。
The server code returning the resources are updated to not only check the header but also the query parameters. of course the token added to the query parameter might be authenticated slightly differently.. e.g. there might be a time window after after a normal rest request in which such a request is allowed etc .. since the url will remain in the browser history.
返回资源的服务器代码被更新,不仅检查标头,还检查查询参数。当然,添加到查询参数中的令牌的认证方式可能略有不同。
回答by Mardie
From oficial documentation at: http://docs.angularjs.org/api/ngResource/service/$resource
来自官方文档:http: //docs.angularjs.org/api/ngResource/service/$resource
Usage
$resource(url, [paramDefaults], [actions]);
[...]
actions: Hash with declaration of custom action that should extend the default set of resource actions. The declaration should be created in the format of $http.config:
{action1: {method:?, params:?, isArray:?, headers:?, ...},
action2: {method:?, params:?, isArray:?, headers:?, ...}, ...}
用法
$resource(url, [paramDefaults], [actions]);
[...]
动作:带有自定义动作声明的散列,应该扩展默认的资源动作集。声明应以 $http.config 的格式创建:
{action1: {method:?, params:?, isArray:?, headers:?, ...},
action2: {method:?, params:?, isArray:?, headers:?, ...}, . ..}
More about $http service:
有关 $http 服务的更多信息:
http://docs.angularjs.org/api/ng/service/$http#usage_parameters
http://docs.angularjs.org/api/ng/service/$http#usage_parameters
回答by Jeffrey Nicholson Carré
As pointed out HereFIrefox supports httpChannel.setRequestHeader:
正如这里指出的Firefox 支持httpChannel.setRequestHeader:
// adds "X-Hello: World" header to the request
httpChannel.setRequestHeader("X-Hello", "World", false);
In the example code above we have a variable named httpChannel which points to an object implementing nsIHttpChannel. (This variable could have been named anything though.)
The setRequestHeader method takes 3 parameters. The first parameter is the name of the HTTP request header. The second parameter is the value of the HTTP request header. And for now, just ignore the third parameter, and just always make it false.
在上面的示例代码中,我们有一个名为 httpChannel 的变量,它指向一个实现 nsIHttpChannel 的对象。(尽管这个变量可以被命名为任何名字。)
setRequestHeader 方法接受 3 个参数。第一个参数是 HTTP 请求头的名称。第二个参数是 HTTP 请求头的值。现在,只需忽略第三个参数,并始终将其设为 false。
However this seems to be only available on Firefox (link)
但是,这似乎仅在 Firefox 上可用(链接)
You can either use Cookies to pass the value and retrieve it as a cookie instead of a HttpHeader or use ajax to retrieve the image with a custom header.
您可以使用 Cookies 来传递值并将其作为 cookie 而不是 HttpHeader 来检索,或者使用 ajax 来检索带有自定义标头的图像。
More links :
更多链接: