简体   繁体   English

"JavaScript 将 [object Object] 转换为 JSON"

[英]JavaScript convert [object Object] to JSON

I am implementing a token based authentication and I need to access the token I have set when i check if the user is authenticated.我正在实现基于令牌的身份验证,当我检查用户是否通过身份验证时,我需要访问我设置的令牌。

I am using this method to check if the user is authenticated:我正在使用这种方法来检查用户是否经过身份验证:

function isAuthenticated(req, res, next) {
    const token = req.headers['authorization'];
    console.log(token);
    if (token) {
        req.token = token;
        next();
    } else {
        res.sendStatus(401);
    }
}

Unfortunately, the string "[object Object]"<\/code> doesn't have enough information to recreate back the original object.不幸的是,字符串"[object Object]"<\/code>没有足够的信息来重新创建原始对象。 You'll have to debug the logic and find out why req.headers['authorization']<\/code> has such value in the first place.您必须首先调试逻辑并找出为什么req.headers['authorization']<\/code>具有这样的价值。

"

Use JSON.stringify使用 JSON.stringify

function isAuthenticated(req, res, next) {
    const token = req.headers['authorization'];
    console.log(JSON.stringify(token));
    if (token) {
        req.token = token;
        next();
    } else {
        res.sendStatus(401);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM