【问题标题】:Add header to http requests made from within html将标头添加到从 html 中发出的 http 请求
【发布时间】:2017-04-01 11:07:31
【问题描述】:

我通过要求它们在请求标头中携带授权令牌来保护我的 api 端点。服务器确保此令牌在每个端点都存在且有效。对于来自客户端代码(Angular 2)的请求,一切正常。

但是来自 html 的请求呢?

...
<img src="api/Videos/{{video.id}}/thumbnail">
...

如何为这些请求添加授权标头?这是一个 Angular 2 应用程序,因此可能有多种解决方案。

【问题讨论】:

    标签: angular http-headers httprequest


    【解决方案1】:

    不确定这是否是您的意思,但您可以创建一个服务来获取所需的数据(来自 HTTP 请求),

     getData() : Observable<Model[]> {
         // ...using get request
         return this.http.get(this.url)
                // ...and calling .json() on the response to return data
                .map((res:Response) => res.json())
                //...errors if any
                .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
     }
    

    和你的模型

    export class Model {
    constructor(
        public id: string, 
        public imagePath: string
        //other properties that you might need..
        ){}
    

    }

    那么你只需要像这样绑定 src 属性

     <img class="img-responsive" src="{{model.imagePath}}" style="max-height: 50px;"/>
    

    请注意,您可以像这样在请求中添加标头

     let headers = new Headers({ 'Content-Type': 'application/json' });
     let options = new RequestOptions({ headers: headers }); // Create a request option 
    

    然后

    return this.http.get(url, {
      headers: headers
    });
    

    【讨论】:

      猜你喜欢
      • 2017-02-15
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多