gpt4 book ai didi

angular - 巢JS : return a string

转载 作者:行者123 更新时间:2023-12-02 18:35:58 26 4
gpt4 key购买 nike

我正在使用@nrwl/Nx创建一个项目。

我成功地将 Angular 和 Nest 项目添加到其中。

然后我尝试测试两者之间的连接。

Angular 代码

content;

testEndpoint() {
this.http.get<any>('api/test').subscribe(res => this.content = res);
}

嵌套代码

@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}

@Get('test')
testConnection(): string {
return 'Some content';
}
}

正如所见,我只是尝试从端点返回一个字符串。在 the documentation ,

Using this built-in method, when a request handler returns a JavaScript object or array, it will automatically be serialized to JSON. When it returns a string, however, Nest will send just a string without attempting to serialize it. This makes response handling simple: just return the value, and Nest takes care of the rest.

很自然地,我希望这能起作用(他们的例子基本上与此相同)。

但是我遇到了以下错误:

error: SyntaxError: Unexpected token S in JSON at position 0 at [...]

尽管HTTP代码是200并且可以在网络选项卡中看到内容。

有人可以向我解释一下这是什么问题吗?

(我尝试向请求添加内容类型 header ,但没有成功)

编辑 1:请求:

enter image description here

最佳答案

看起来 HttpClient 只是忽略服务器发送的内容类型,尝试始终将响应视为 JSON。这很奇怪,但值得庆幸的是,您可以显式指定预期的响应类型来覆盖它,如 the docs 中所述。 .

this.http.get('api/test', {responseType: 'text'})

需要注意的是,您必须删除泛型部分(或以其他方式删除类型),因为 this issue .

The generic MUST not be used when responseType is specified to something other than 'json' because typeof T will then be inferred automatically.

关于angular - 巢JS : return a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57257091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com