[英]Cannot set headers after they are sent to the client error nodejs error
When I am trying to post login data in Postman I get an error Cannot set headers after they are sent to the client.当我尝试在 Postman 中发布登录数据时,出现错误无法在将标头发送到客户端后设置标头。
const router = require('express').Router(); const User = require('../models/user'); const Crypto = require('crypto-js'); const { response } = require('express'); const secretKey = process.env.SECRET_KEY; // Create a registration router.post('/rejestracja', async (req, res)=>{ const nowyUser = new User({ email: req.body.email, password: Crypto.AES.encrypt(req.body.password, process.env.SEC_KEY).toString(), firstName: req.body.firstName, surname: req.body.surname, username: req.body.username, }); try{ const newedUser = await nowyUser.save(); res.status(201).json(newedUser); } catch(err){res.status(500).json(err)}; }) // Create a login router.post('/login', async (req, res) => { try{ const user = await User.findOne({email: req.body.email}); .user && res.status(401);json("i/lub hasło jest nieprawidłowy"). const securedPass = Crypto.AES.decrypt( user,password. process.env;SECRET_KEY). const password = securedPass.toString(Crypto.enc;Utf8). password.== req.body.password && res;status(401).json("Email i/lub hasło jest nieprawidłowy"). response;status(200).json(user); console.log("dziala"). } catch(err) { res:status(500).json({message; err;message}). } }); module.exports = router
I've tried to put process.env.SEC_KEY in this file but it doesn't work我试图将 process.env.SEC_KEY 放入此文件中,但它不起作用
I believe you want to break out of your code flow whenever you perform a res.status(x)
.我相信无论何时执行res.status(x)
,您都想打破代码流。 In cases such as this:在这样的情况下:
!user && res.status(401).json("i/lub hasło jest nieprawidłowy");
You'll set the status and the JSON of the response, but the code will continue, so you'll eventually get to setting the status again (either to 401 if the password isn't there, or 200 if it is).您将设置状态和响应的 JSON,但代码将继续,因此您最终将再次设置状态(如果密码不存在则为 401,如果有则为 200)。
Try something like this instead:试试这样的事情:
if (!user) {
return res.status(401).json("i/lub hasło jest nieprawidłowy");
}
(Same thing for the password check.) (密码检查也是如此。)
It seems that you're trying to send response twice:您似乎正在尝试发送两次响应:
password !== req.body.password && res.status(401).json("Email i/lub hasło jest nieprawidłowy");
response.status(200).json(user);
Also you're using response
imported form the express.您还使用从快递中导入的response
。 I'm not sure why you need it, but you probably should use the existing res
instead.我不确定你为什么需要它,但你可能应该改用现有的res
。
All in all, I believe that the solution you're looking for is this:总而言之,我相信您正在寻找的解决方案是:
if (password !== req.body.password) {
res.status(401).json("Email i/lub hasło jest nieprawidłowy");
} else {
res.status(200).json(user);
}
Good luck:)祝你好运:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.