【发布时间】:2018-02-07 21:15:03
【问题描述】:
我在 ExpressJS 中有一个 API。在该 API 中,我有一个登录端点,当发布到该端点时,我不断收到异常,即标头在发送后无法设置。
我知道这通常是一个回调,它被调用了两次,或者没有从设置了标头的东西正确返回,导致应用程序尝试再次设置它们,但是在我的 /login 端点中我没有这样做。
我不明白为什么会发生这种情况,我很想知道为什么当我读到相同的回复和答案时,我快要拔掉头发了。我希望这是我明显缺少的东西。
import User from '../../models/user';
import { Router } from 'express';
import jwt from 'jsonwebtoken';
export default () => {
const route = Router();
route.post('/create', async (req, res, next) => {
if (!req.body.email || !req.body.password) {
return res
.status(400)
.json({ message: 'username or password is missing' });
}
const { email, password } = req.body;
const count = await User.count({ email });
if (count > 0) {
return res.status(409).json({ message: 'email must be unique' });
}
const newUser = await new User({ email, password });
const doc = await newUser.save();
return res.status(201).json({ type: 'account', attributes: doc });
});
route.post('/login', async (req, res, next) => {
if (req.body.email && req.body.password) {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (user) {
user.comparePassword(password, isMatch => {
if (isMatch) {
const token = jwt.sign(
{ sub: user.id, roles: [], email: user.email },
process.env.SECRET_KEY,
{ expiresIn: '12h' },
);
return res
.status(200)
.json({ type: 'account', attributes: { token } });
}
});
}
}
res.sendStatus(401);
});
return route;
};
【问题讨论】:
标签: node.js express passport.js