【问题标题】:How to change axios content from "text/html" to application/json type in Nestjs如何在 Nestjs 中将 axios 内容从“text/html”更改为 application/json 类型
【发布时间】:2020-09-20 16:50:10
【问题描述】:

我发现 axios 返回的是字符串而不是有效的 json。

headers:Object {date: "Tue, 02 Jun 2020 08:44:06 GMT", server: "Apache", connection: "close", …}
connection:"close"
content-type:"text/html; charset=UTF-8"
date:"Tue, 02 Jun 2020 08:44:06 GMT"
server:"Apache"
transfer-encoding:"chunked"

如何在 NestJs 应用程序中将 content-type 更改为 application/json? 我试过了,但没有用

 const meterInfo = await this.httpService.get(url, { headers: { "Content-Type": "application/json" } }).toPromise();

这是返回的无效 json。

"{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Utility","minimumAmount":"13897"},"response_hash":"c43c9d74480f340f55156f6r5c56487v8w"}"

【问题讨论】:

    标签: node.js json axios nestjs httpservice


    【解决方案1】:

    您应该发送具有相同 MIME 类型的 Accept 标头,而不是发送 Content-Type 标头。这会告诉服务器您希望收到什么,如果内容协商设置正确,它将允许您返回 JSON 而不是那个奇怪的字符串。

    this.httpService.get(
      url,
      {
        headers: {
          'Accept': 'application/json',
        },
      },
    ).toPromise();
    

    如果这不起作用,您需要提供自己的序列化程序以将字符串从那种不稳定的格式转换为 JSON,与服务器管理员联系,看看他们是否可以为您提供有关如何使用其 API 的更好文档。

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 2023-03-14
      • 2014-09-17
      相关资源
      最近更新 更多