我正在本地测试一些google云功能,方法是在角和云函数中创建一个小型测试应用程序。当我发出一个post请求时,我试图从云函数中读取响应。然后,云函数返回一个错误,其中包含数据,而不仅仅是实际数据。奇怪的是,如果我不订阅服务器的响应,那么我就不会在控制台中看到错误,这意味着它必须是云函数本身的一个设置。但是,我直接从文档中复制和粘贴了云函数代码。请帮帮忙。
TL;DR: Http云-函数返回错误而不是数据,为什么?
下面是云函数的代码:
exports.helloWorld = functions.https.onRequest((request, response) => {
response.header('Access-Control-Allow-Origin', '*');
response.status(200).send('poop');
});下面是测试帖子的代码:
test() {
var req = this.http
.post(
'http://localhost:5000/merchantapi-b7b17/us-central1/helloWorld',
JSON.stringify({ poop: 'poop' })
)
.subscribe(_val => {
console.log(_val);
});
}下面是我在控制台上遇到的错误:
HttpErrorResponse
error: {error: SyntaxError: JSON Parse error: Unexpected identifier "poop", text: "poop"}
headers: HttpHeaders {normalizedNames: Map, lazyUpdate: null, lazyInit: function}
message: "Http failure during parsing for http://localhost:5000/merchantapi-b7b17/us-central1/helloWorld"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:5000/merchantapi-b7b17/us-central1/helloWorld"
HttpErrorResponse Prototype
defaultErrorLogger — core.js:6014
handleError — core.js:6066
next — core.js:40558
(anonymous function) — core.js:35336
__tryOrUnsub — Subscriber.js:185
next — Subscriber.js:124
_next — Subscriber.js:72
next — Subscriber.js:49
next — Subject.js:39
emit — core.js:35298
run — zone-evergreen.js:124
onHandleError — core.js:39735
runTask — zone-evergreen.js:171
invokeTask — zone-evergreen.js:465
timer — zone-evergreen.js:2650
defaultErrorLogger — core.js:6014正如您所看到的,错误包含数据,我可以使用它,但我想了解它为什么发送错误,以及如何压缩它。
发布于 2020-03-25 16:07:26
默认情况下,HttpClient的现代JSON需要一个JSON响应,而字符串'poop‘不是有效的JSON。
要解决这个问题,需要将有效的JSON发送回客户端:
exports.helloWorld = functions.https.onRequest((request, response) => {
response.header('Access-Control-Allow-Origin', '*');
response.status(200).send({'message':'poop'});
});有效的json:
{
"message": "poop"
}https://stackoverflow.com/questions/60852392
复制相似问题