Angular的Http调用标题显示200响应,但响应数据显示HTML而不是JSON数据。
创始人
2024-10-24 05:00:31
0

问题可能是由于服务器返回的Content-Type标头不正确导致的。服务器可能错误地将响应标记为HTML而不是JSON。

要解决此问题,您可以使用Angular的拦截器来更改响应的Content-Type标头。以下是一个示例:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class ContentTypeInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    return next.handle(request).pipe(
      map(response => {
        if (response instanceof HttpResponse && response.headers.get('Content-Type') === 'text/html') {
          // 将Content-Type标头更改为application/json
          response = response.clone({ headers: response.headers.set('Content-Type', 'application/json') });
        }
        return response;
      })
    );
  }
}

然后,在您的模块中将拦截器添加到提供者列表中:

import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ContentTypeInterceptor } from './content-type.interceptor';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ContentTypeInterceptor,
      multi: true
    }
  ]
})
export class AppModule { }

通过这样做,拦截器将检查每个响应的Content-Type标头,如果标头为text/html,则将其更改为application/json。这样,您就可以确保接收到的响应数据为JSON格式。

相关内容

热门资讯

透视辅助"aapok... 透视辅助"aapoker脚本"本来是有辅助软件(哔哩哔哩)1、下载好aapoker脚本透视辅助下载之...
透视专业"wepok... 透视专业"wepoker私人局规律"真是真的有辅助器(哔哩哔哩)1、每一步都需要思考,不同水平的挑战...
透视解密"pokem... 透视解密"pokemmo辅助器手机版下载"切实是真的辅助方法(哔哩哔哩)1)pokemmo辅助器手机...
透视普及"wepok... 透视普及"wepoker透视底牌"原来真的有辅助技巧(哔哩哔哩)1、wepoker透视底牌有没有辅助...
透视教你"wepok... 透视教你"wepoker轻量版透视方法"总是是真的辅助挂(哔哩哔哩)1、进入到wepoker轻量版透...
透视揭幕"wepok... 透视揭幕"wepoker插件功能辅助器"其实是真的辅助技巧(哔哩哔哩)1、操作简单,无需wepoke...
透视开挂"wpk插件... 透视开挂"wpk插件"一直存在有辅助器(哔哩哔哩)1、操作简单,无需wpk插件手机版透视脚本,只需要...
透视解谜"aapok... 透视解谜"aapoker辅助器是真的吗"好像是真的辅助插件(哔哩哔哩)1、首先打开aapoker辅助...
透视揭幕"hhpok... 透视揭幕"hhpoker有后台操控吗"好像是真的辅助技巧(哔哩哔哩)1、起透看视 hhpoker有后...
透视揭幕"wepok... 透视揭幕"wepokerplus辅助"本来有辅助神器(哔哩哔哩)wepokerplus辅助破解侠是真...