【发布时间】:2019-10-10 02:14:46
【问题描述】:
我正在建立一个社交网络来学习 nodejs 和 reactjs。目前,在使用邮递员在/signin 调试中构建后端时,我什至无法启动节点服务器,cmd 抛出以下错误:
\node_react\2\nodeapi\controllers\auth.js:40
const {_id, name, email} = user;
^
SyntaxError: Identifier 'email' has already been declared
引发错误的代码sn-p如下:
//generate a token with user id and secret
const token = jwt.sign({_id: user._id}, process.env.JWT_SECRET);
//persist the token as 't' in cookie with expiry date
res.cookie("t", token, {expire: new Date() + 9999});
//return response with user and token to frontend client
const {_id, name, email} = user;
return res.json({token, user:{_id, email, name}});
完整的auth.js代码如下:
const jwt = require("jsonwebtoken");
require ('dotenv').config();
const User = require("../models/user");
exports.signup = async (req, res) => {
const userExists = await User.findOne({email: req.body.email});
if(userExists)
return res.status(403).json({
error: "Email is taken!"
});
const user = await new User(req.body);
await user.save();
res.status(200).json({ message: "Signup success! Please login:)" });
};
exports.signin = (req,res) => {
//find the user based on email
const { email, password } = req.body
User.findOne({email}, (err, user) => {
//if error or no user
if (err || !user) {
return res.status(401).json({
error: "User with that email does not exists. Please signin."
});
}
//if user is found make sure the email and password match
// create authenticate method in model and use here
if (!user.authenticate(password))
return res.status(401).json({
error: "Email and password do not match."
});
})
//generate a token with user id and secret
const token = jwt.sign({_id: user._id}, process.env.JWT_SECRET);
//persist the token as 't' in cookie with expiry date
res.cookie("t", token, {expire: new Date() + "9999"});
//return response with user and token to frontend client
const {_id, name, email} = user;
return res.json({token, user:{_id, email, name}});
}
【问题讨论】:
-
您似乎在此分配之前定义了
email。你能提供所有的auth.ts代码吗? -
不相关但
new Date() + 9999将是字符串连接而不是算术。 -
添加了 auth.js 代码@GustavoLopes
-
在我的情况下,我正在导出我导入的东西......同名......只需为此执行
export { curry as curry }。逻辑是外部依赖可以在不需要重构的情况下进行全局扩展、交换和集中替换。具体错误:SyntaxError: Identifier 'curry' has already been declared
标签: node.js typescript express postman