【问题标题】:How to chage content-type in interceptor in angular 6?如何在 Angular 6 中更改拦截器中的内容类型?
【发布时间】:2018-08-26 14:56:53
【问题描述】:

有些服务需要有token,有些有不同的Content-Type。我应该如何在Interceptor文件中管理它们?

【问题讨论】:

    标签: angular6 angular-http-interceptors


    【解决方案1】:

    您可以在拦截器函数上获取或设置所有请求标头。以下代码揭示了用于处理此更改的标头属性:

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
        if (request.headers.has('Content-Type'))
           contentType = request.headers.get('Content-Type');
    
        request = request.clone({
          setHeaders: {
            'Authorization': `Bearer ${this.auth.getToken()}`,
            'Content-Type': (contentType != 'application/json' ? 'application/text' :  contentType)
          }
        });
        return next.handle(request);
      }
    

    【讨论】:

    • if (request.headers.has('Content-Type')) 条件始终为假。我以这种方式在服务中设置标头: var headers = new HttpHeaders(); headers.append('Content-Type', 'application/x-www-form-urlencoded');常量 httpOptions = { 标头:标头 };返回 this.http.post(this.tokenUrl, body, httpOptions)
    • 您应该在指定的 HTTP 方法上设置请求标头(例如 HttpClient.Get&lt;T&gt;(url, options) )。这是这种用法的一个示例:return this.http.get&lt;T&gt;(this.path, { params: this.getHttpParams(params), responseType: type, headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
    • 如果你没有在请求头设置你的请求内容类型,你可以在你的HTTP拦截器上设置它。
    • 检查您的开发者网络日志并注意请求。在正确的标头定义中,您将在开发人员控制台上看到content-type 以请求您的请求。否则再次检查您的请求标头定义。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多