JWT错误类型错误:’instanceof’的右侧不是对象

huangapple go评论76阅读模式
英文:

JWT ERROR TypeError: Right-hand side of 'instanceof' is not an object

问题

I'm trying to create an application with express and JWT (JsonWebToken). It works locally, but when I try to use it on my home server, it gives an error. I spent about an hour trying to find a solution, but nothing works.

TypeError: Right-hand side of 'instanceof' is not an object
    at Object.module.exports [as sign] (/home/container/node_modules/jsonwebtoken/sign.js:108:58)
    at server.post (/home/container/server.js:51:9)
    at Layer.handle [as handle_request] (/home/container/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/container/node_modules/express/lib/router/route.js:144:13)
    at Route.dispatch (/home/container/node_modules/express/lib/router/route.js:114:3)
    at Layer.handle [as handle_request] (/home/container/node_modules/express/lib/router/layer.js:95:5)
    at /home/container/node_modules/express/lib/router/index.js:284:15
    at Function.process_params (/home/container/node_modules/express/lib/router/index.js:346:12)
    at next (/home/container/node_modules/express/lib/router/index.js:280:10)
    at /home/container/node_modules/body-parser/lib/read.js:137:5

It is a really simple application, but I can't find out why it gives the error above ^^

This is my code:

const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');

const server = express();
const port = 3000 || process.env.PORT;

server.options('*', cors());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));

const jwt = require('jsonwebtoken');

server.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

const posts = [
    {
        user: 'david',
        title: 'post'
    },
    {
        user: 'bryan',
        title: 'post2'
    }
];

server.get('/posts', authenticateToken, (req, response) => {
    response.json(posts.filter(post => post.user === req.user));
});

server.post('/login', (req, res) => {
    const { username, password } = req.body;
    if (username == null) return res.sendStatus(401);

    jwt.sign(username, 'test', (err, token) => {
        if (err) {
            console.log(err);
            return res.sendStatus(403);
        }

        console.log(accessToken);
        res.json({ accessToken: accessToken });
    });
});

function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (token == null) return res.sendStatus(401);
    jwt.verify(token, 'test', (err, user) => {
        if (err) return res.sendStatus(403);
        req.user = user;
        next();
    });
}

I cannot find a solution on any website.

英文:

Im trying to create an application with express and JWT (JsonWebToken). It works localy but when i try to use it on my server at home it gives an error. I spend like an hour trying to find a solution but nothing works.

TypeError: Right-hand side of 'instanceof' is not an object
at Object.module.exports [as sign] (/home/container/node_modules/jsonwebtoken/sign.js:108:58)
at server.post (/home/container/server.js:51:9)
at Layer.handle [as handle_request] (/home/container/node_modules/express/lib/router/layer.js:95:5)
at next (/home/container/node_modules/express/lib/router/route.js:144:13)
at Route.dispatch (/home/container/node_modules/express/lib/router/route.js:114:3)
at Layer.handle [as handle_request] (/home/container/node_modules/express/lib/router/layer.js:95:5)
at /home/container/node_modules/express/lib/router/index.js:284:15
at Function.process_params (/home/container/node_modules/express/lib/router/index.js:346:12)
at next (/home/container/node_modules/express/lib/router/index.js:280:10)
at /home/container/node_modules/body-parser/lib/read.js:137:5

It is a really a simple application but i can't find out why it gives the error above ^^

This is my code:

const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const server = express();
const port = 3000 || process.env.PORT;
server.options('*', cors());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
const jwt = require('jsonwebtoken');
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
const posts = [
{
user: 'david',
title: 'post'
},
{
user: 'bryan',
title: 'post2'
}
];
server.get('/posts', authenticateToken, (req, response) => {
response.json(posts.filter(post => post.user === req.user));
});
server.post('/login', (req, res) => {
const {username, password} = req.body;
if(username == null) return res.sendStatus(401);
jwt.sign(username, 'test', (err, token) => {
if(err) {
console.log(err);
return res.sendStatus(403);
}
console.log(accessToken);
res.json({accessToken: accessToken});
});
});
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if(token == null) return res.sendStatus(401);
jwt.verify(token, 'test', (err, user) => {
if(err) return res.sendStatus(403);
req.user = user;
next();
});
}

I cannot find a solution on any website.

答案1

得分: 1

我遇到了同样的问题。我发现当运行 npm audit fix 命令以消除漏洞时,问题出现了。

该过程更新了护照模块,似乎是问题的原因。我回到应用修复之前的设置,一切都正常工作了。

差异:

"passport": "~0.2.0",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"passport-jwt": "^4.0.1",

相当老的 Node 版本:10.16.0

希望有所帮助。

英文:

I had the same problem. I found out that the problem appeared when running the npm audit fix command to get rid of the vulnerabilities.

The process updated passport module and that seemed to be the cause of the problem. I went back to the settings before applying the fix and everything worked fine again.

Diff:

"passport": "~0.2.0",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"passport-jwt": "^4.0.1",

Fairly old node version: 10.16.0

I hope it helps

答案2

得分: 1

使用一个新的(对我来说新的)代码库。我一直遇到这个问题。我升级了所有东西到最新版本,但仍然出现相同的错误。

```sh
$ grep jsonwebtoken package.json
    "jsonwebtoken": "^9.0.0",
    "@types/jsonwebtoken": "9.0.1",

$ node --version
v19.6.0

删除了 node_modules 文件夹,运行了 npm install 并重新启动了 npm run dev

TypeError: 'instanceof' 的右侧不是一个对象

现在已经过去一天多了,我真的需要一些帮助!


<details>
<summary>英文:</summary>
Working with a new (to me) codebase. I keep running into this. I upgraded everything to the latest, but have the same errors.
```sh
$ grep jsonwebtoken package.json
&quot;jsonwebtoken&quot;: &quot;^9.0.0&quot;,
&quot;@types/jsonwebtoken&quot;: &quot;9.0.1&quot;,
$ node --version
v19.6.0

deleted node_modules, ran npm install and restarted npm run dev

>TypeError: Right-hand side of 'instanceof' is not an object

It's been over a day now, I can really do with some help here!

答案3

得分: 0

我更新了服务器上的Node版本,问题得到解决。

英文:

I updated the node version on the server and it fixed the error.

答案4

得分: 0

我遇到了同样的问题。问题是 jsonwebtoken 包的版本 9.0.0 不支持 Node 版本 11 及以下,所以我通过将 jsonwebtoken 包的版本降级解决了这个问题。

我是通过在 package.json 文件中将 jsonwebtoken 依赖从 9.0.0 改为 8.5.1,然后在终端中运行 npm update 来完成的。

这里可能建议升级您的 Node 版本,但由于一个 npm 问题,我尚未成功升级我的 Node 版本,所以这只是一个临时解决方法。

查看下面的文章,解释了从 jsonwebtoken 包的 v8 升级到 v9 的迁移过程。https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9

英文:

I had the same issue. The issue being that version 9.0.0 of the jsonwebtoken package does not support node version 11 and below, so I solved it by downgrading the version of the jsonwebtoken package.

I did so by changing the jsonwebtoken dependency from 9.0.0 to 8.5.1 inside the package.json file, then I ran npm update inside my terminal.

Upgrading your node version might be recommended here, but I haven't quite managed to update my node version because of an npm issue, so this is only a workaround.

Checkout the following article explaining the migration from v8 to v9 of the jsonwebtoken package. https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9

huangapple
  • 本文由 发表于 2023年1月5日 21:39:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75019306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定