我有一个空的 Angular 应用程序,只是一个应用程序组件,里面没有任何花哨的东西。
我有一个函数可以对 REST API 运行 GET 请求。该请求仅用于测试目的,因此它不执行任何操作并返回一些模拟数据。我使用 Angular 的
HttpClient
来提出该请求。
在生命周期中
ngOnInit
我运行该函数并且它工作正常。
页面中有一个按钮可以运行相同的功能。当我使用该按钮时,出现错误:
Status : 0
Error : TypeError: Failed to fetch
at http://localhost:55651/polyfills.js:1255:30
at proto.<computed> (http://localhost:55651/polyfills.js:782:16)
at _FetchBackend.<anonymous> (http://localhost:55651/@fs/C:/Users/morgan/issue/.angular/cache/17.3.2/vite/deps/chunk-EONTFRYP.js?v=baac2411:1128:35)
at Generator.next (<anonymous>)
at http://localhost:55651/@fs/C:/Users/morgan/issue/.angular/cache/17.3.2/vite/deps/chunk-KJBDP7EP.js?v=baac2411:49:61
at new ZoneAwarePromise (http://localhost:55651/polyfills.js:1185:21)
at __async (http://localhost:55651/@fs/C:/Users/morgan/issue/.angular/cache/17.3.2/vite/deps/chunk-KJBDP7EP.js?v=baac2411:33:10)
at _FetchBackend.doRequest (http://localhost:55651/@fs/C:/Users/morgan/issue/.angular/cache/17.3.2/vite/deps/chunk-EONTFRYP.js?v=baac2411:1124:12)
at Observable2._subscribe (http://localhost:55651/@fs/C:/Users/morgan/issue/.angular/cache/17.3.2/vite/deps/chunk-EONTFRYP.js?v=baac2411:1117:12)
at Observable2._trySubscribe (http://localhost:55651/@fs/C:/Users/morgan/issue/.angular/cache/17.3.2/vite/deps/chunk-KJBDP7EP.js?v=baac2411:1131:19)
如果我从 shell 运行相同的 GET 请求,则没有任何问题。
我的 nginx access.log 显示这些行:
MY-IP - - [07/Apr/2024:14:12:58 +0000] "GET /tmpTest HTTP/1.1" 200 26 "-" "node"
My-IP - - [07/Apr/2024:14:13:00 +0000] "GET /tmpTest HTTP/1.1" 200 26 "http://localhost:55651/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 OPR/108.0.0.0"
所以第一次,如果我理解正确的话,请求是由节点发出的,第二次是用我的浏览器发出的(这是有道理的)。我不确定这是否重要,但我不知道该去哪里寻找。
请注意,当 Rest Api(用 Flask 制作)在本地提供时,我没有遇到问题。但当它在服务器上时(使用 nginx 和gunicorn)就会出现这种情况。
我做了一个 stackblitz,但是当我用它运行应用程序时,在两种情况下都出现错误(使用
ngOnInit
和按钮):https://stackblitz.com/edit/stackblitz-starters-r5psb2?file =src%2Fmain.ts
我知道这是一个新手问题,对此我很抱歉,但我完全陷入困境......
当您的 HTTP 请求标头声称内容经过 gzip 编码,但事实并非如此时,就会发生这种情况。如果您在浏览器中执行常规请求并检查请求,您将看到标头:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Host:34.163.40.91:5000
Upgrade-Insecure-Requests: 1