我有以下代码
const express = require('express');
const jwt = require('express-jwt');
const app = express();
// Middleware to authenticate requests using JWT
app.use(jwt({
secret: 'your-secret-key'
}).unless({
path: ['/login']
}));
// Example route that requires authentication
app.get('/protected', (req, res) => {
// If the request reaches here, it means it's authenticated`
res.send('You are authenticated!');
});
// Example route for logging in and obtaining JWT token
app.post('/login', (req, res) => {
// Logic to authenticate user and generate JWT token
// Once authenticated, send back JWT token
const token = jwt.sign({
username: 'exampleUser'
}, 'your-secret-key');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
我收到此错误。
类型错误:jwt 不是函数
我尝试了chatGPT和Gemeni,但无法解决问题。
导入jwt方式的问题:
const jwt = require('express-jwt');
正确做法:
const express = require('express');
const { expressjwt: jwt } = require('express-jwt');
const app = express();
// Middleware to authenticate requests using JWT
app.use(jwt({
secret: 'your-secret-key'
}).unless({
path: ['/login']
}));
// the rest of the code...
app.listen(3000, () => {
console.log('Server is running on port 3000');
});