gpt4 book ai didi

javascript - res.jwt 不是一个函数 - NodeJS Express

转载 作者:行者123 更新时间:2023-12-01 02:08:57 27 4
gpt4 key购买 nike

我不断得到

res.jwt is not a function 

我已经安装了jwt-express并像这样导入

import jwt from 'jwt-express'  

这是我的auth.js

import Account from '../services/account.js'
import env from 'dotenv'
import _ from 'lodash'

const dotenv = env.config();

module.exports = {
/**
* Process the user login, generating and returning a token if successful.
*
* @return {res}
*/
async login(req, res, next) {
try {
let origin = req.headers.origin;
let accounts = await Account.getAccounts();

let account = _.find(accounts, {
'email_address' : req.body.username,
'password' : req.body.password
});

if (!account) {
res.send('Username/Password Wrong');
}

// res.send(account);

let authentication = res.jwt({
'email': account.email_address,
'id': account.account_id
});
res.send(authentication);

} catch (error) {
next(error)
}
}
};
<小时/>

index.js

import express from 'express'
import favicon from 'serve-favicon'
import path from 'path'
import bodyParser from 'body-parser'
import bluebird from 'bluebird'
import jwt from 'jwt-express'
import env from 'dotenv'

//Controllers
import fortinetController from './controllers/fortinet'
import authController from './controllers/auth.js'

//Logger
import logger from './config/logger.js'

//Constant
const router = express.Router();
const app = express();
const PORT = 3000;
const dotenv = env.config();
Promise = bluebird;

app.use(bodyParser.urlencoded({extended: true }));
app.use(bodyParser.json());
app.use(router)
app.use(express.static('public'))
app.use(favicon(path.join(__dirname,'public','favicon.ico')))
app.use(jwt.init('CARWASH', {cookies: false }));


router.get('/', (req,res) => {
res.send('Welcome to the backend provisioning daemon to program FortiManager')
});

router.post('/login', authController.login);

//Fortinet
router.post('/fortinet/login', fortinetController.login);
router.post('/fortinet/getSessionTimeOut', fortinetController.getSessionTimeOut);
router.post('/fortinet/logout', fortinetController.logout);

//Error handling function
app.use((err,req,res,next) => {
console.error(err.stack)
res.status(500).send(`Red alert! Red alert!: ${err.stack}`)
logger.error(`${req.method} ${req.url} - ${err.log || err.message}`);
});

app.listen(PORT, () => {
console.log(`Your server is running on ${PORT}`)
}
);

如何调试这个?

<小时/>

更新

我尝试添加这个

console.log(jwt);

我得到了

[nodemon] 1.17.3                                                                                        
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `babel-node ./index.js`
{ active: [Function: active],
clear: [Function: clear],
create: [Function: create],
init: [Function: init],
options:
{ cookie: 'jwt-express',
cookieOptions: { httpOnly: true },
cookies: false,
refresh: true,
reqProperty: 'jwt',
revoke: [Function: revoke],
signOptions: {},
stales: 900000,
verify: [Function: verify],
verifyOptions: {} },
require: [Function: require],
valid: [Function: valid] }
Your server is running on 3000

最佳答案

  1. 您没有正确配置 express-jwt
  2. 您使用的 express-jwt 完全错误。

让我们逐一讨论一下。

我不确定为什么您认为在文档 here 时需要调用 jwt.init(...)状态简单地执行:jwt(...)。因此您需要进行以下更改:

改变

app.use(jwt.init('CARWASH', {cookies: false }));

app.use(jwt({secret: 'CARWASH'}));

不存在 cookies 选项,不确定您从哪里获得该选项。

现在 express-jwt 将仅处理 JWT 的验证。它不会生成 JWT,就像您在 auth.js 中尝试执行的那样。

为了生成 JWT,您将需要另一个模块:jsonwebtoken 。然后,您将在 auth.js 中使用该模块,如下所示:

import jwt from "jsonwebtoken";
// ...

module.export = {
async login(req, res, next) {
try {
// ... auth logic omitted

// Here we generate the JWT
// Make sure the JWT secret is the SAME secret you used for express-jwt
let authentication = jwt.sign({
'email': account.email_address,
'id': account.account_id
}, 'CARWASH');
res.send(authentication);
}
catch (error) {
next(error);
}
}
}

关于javascript - res.jwt 不是一个函数 - NodeJS Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49883957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com