首页 > 解决方案 > [ERR_INVALID_ARG_TYPE]:第一个参数必须是字符串类型或 Buffer 的实例。使用 admin.auth().verifyIdToken 时

问题描述

我正在编写一个后端服务器(使用 Node.js)让用户与 Firebase 交互。这是我到目前为止所拥有的:

但是,我真的很想知道,每次用户登录时,他们都会有一个全新的 idToken(持续 1 小时);那么当新的 idToken 生成时,旧的会立即过期吗?所以,我想我会使用 firebase-admin SDK verifyIdToken 函数来做我需要的事情。

问题是,即使我输入了新的 idToken,该功能也会失败。我真的不知道这里发生了什么。

如果我不执行捕获,这是错误:

(node:9240) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer. Received type number (1598554002)
at write_ (_http_outgoing.js:653:11)
at ServerResponse.write (_http_outgoing.js:621:15)
at D:\Viet Properties\Coding\ViMath\spreadsheet.js:315:19
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async verifyid (D:\Viet Properties\Coding\ViMath\spreadsheet.js:314:5)
at async Server.<anonymous> (D:\Viet Properties\Coding\ViMath\spreadsheet.js:584:17)
(node:9240) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag`--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:9240) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是我调用的函数:

async function verifyid(data, serverres) {
   serverres.write(data.id);
   await admin.auth().verifyIdToken(data.id).then(function(token) {
       serverres.write(token.exp)
   }).catch(function(error) {
       serverres.write(`Error code: ${error.code} \r\nError message: ${error.message}`);
   });
};

主要代码在这里:

var server = http.createServer(async function (req, res) {
    var urllink = url.parse(req.url, true);
    var urldata = urllink.query;

    if (Object.entries(urldata).length !== 0){
        switch(urldata.goal){
            //I dropped some cases here for clearance of the code
            case 'verifyid':
                await verifyid(urldata, res)
                res.end();
                break;
            default:
                res.write("Error: No action has been specified!")
                res.end();
        };
    };
  });


//initialize admin
var admin = require('firebase-admin');
var serviceAccount = require("./vimath_serviceAccountKey.json");
const { parse } = require('path');
const { userInfo } = require('os');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://[my project].firebaseio.com'
});

server.listen(8080);

你们可以看看吗?

非常感谢您,

祝你有愉快的一天, 在此处输入图像描述 在此处输入图像描述

标签: javascriptnode.jsfirebasefirebase-authenticationfirebase-admin

解决方案


在这一行抛出错误:

serverres.write(token.exp)

该 API 需要一个字符串或一个缓冲区,但您传递的是一个数字。


推荐阅读