使用数据存储的分页示例会导致" Error: 13 INTERNAL: Request message serialization failure: invalid encoding"



我将使用此页面作为起点。

我的代码如下:

app.get('/gizmos', async (req, res, next) => {
const pageSize = 3;
const resText = [];
const cursor = req.query.cursor;
try {
let query = datastore.createQuery('gizmo').limit(pageSize);
if (cursor) {
query = query.start(cursor);
}
const [results] = await datastore.runQuery(query);
const [gizmos] = results[0];
const info = results[1];
if (info.moreResults !== Datastore.NO_MORE_RESULTS) {
// If there are more results to retrieve, the end cursor is
// automatically set on `info`. To get this value directly, access
// the `endCursor` property.
const nextUrl = req.protocol + "://" + req.get("host") + req.baseUrl + "?cursor=" + info.endCursor;
console.log(nextUrl);
}
gizmos.forEach(gizmo => {
const id = gizmo[Datastore.KEY].id;
resText.push({
"id" : id,
"name" : gizmo.name,

});
});
res
.status(200)
.set('Content-Type', 'text/plain')
.send(resText)
.end();
} catch (error) {
next(error);
}
});

但它以500错误而失败。日志上写着:

错误:13内部:请求消息序列化失败:无效在Object.callErrorFromStatus进行编码(/workspace/nod_module/@grpc/grpc-js/build/src/call.js:31:26(
在Object.onReceiveStatus(/workspace/nod_module/@grpc/grpc-js/build/src/client.js:176:52(
在Object.onReceiveStatus(/workspace/nod_module/@grpc/grpc-js/build/src/client-interceptors.js:336:141(在Object.onReceiveStatus(/workspace/nod_module/@grpc/grpc-js/build/src/client-interceptors.js:299:181(在/workspace/nod_module/@grpc/grpc-js/build/src/call-stream.js:145:78在processTicksAndRejections(internal/process/task_queues.js:75:11(

有什么想法吗?

将其作为社区wiki发布,因为它基于@JimMorrison的评论。

这里的问题是,您在res.send()中传递了一个数组,但在给定text/plain内容类型的情况下,它需要一个字符串,因此您需要在此处使用此数组之前将其转换为字符串。你可以通过使用以下代码来做到这一点:

res
.status(200)
.set('Content-Type', 'text/plain')
.send(JSON.stringify(resText))
.end();

info.endCursor可能包含保留字符

var set1 = ";,/?:@&=+$"; // Reserved Characters

将http请求的代码更改为"?cursor=" + encodeURIComponent(info.endCursor);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

看起来您是通过查询字符串传递光标的,该字符串应该通过encodeURIComponent/decodeURIComponent进行编码和解码。

解码:

if (cursor) {
query = query.start(decodeURIComponent(cursor));
}

编码:

encodeURIComponent(info.endCursor)

相关内容

最新更新