Reputation: 1
< Here what error I am getting on vs code
Cannot set headers after they are sent to the client
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (D:\Jwt\server\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (D:\Jwt\server\node_modules\express\lib\response.js:174:12)
at D:\Jwt\server\routes\jwtAuth.js:31:21
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
} >
<` Here is my routes/jwtAuth.js file where I put all restful api and token api to generate
token in postman but I do not know why its just adding new user into the database while it
has to show the token in the postmand
const router =require("express").Router();
const pool = require("../db");
const bcrypt = require("bcrypt");
const jwtGenerator = require("../utils/jwtGenerator");
router.post("/register",async(req,res) => {
try{
const {name,email,password } = req.body;
const user =await pool.query("SELECT * FROM users WHERE user_email =$1", [email]);
if(user.rows.length != 0){
return res.status(401).send("User already exist");
}
const saltRound =10;
const salt = await bcrypt.genSalt(saltRound);
const bcryptPassword = await bcrypt.hash(password,salt);
const newUser = await pool.query("INSERT INTO users (user_name,user_email,user_password)
VALUES($1,$2,$3) RETURNING *",[name,email,bcryptPassword]);
res.json(newUser.rows[0]);
const token = jwtGenerator(newUser.rows[0].user_id);
res.json({ token });
} catch(err){
console.error(err.message);
res.status(500).send("Server error");
}
})
module.exports = router;` >
< `Here is jwtAuth.js files to generate the token maybe something wrong over here that's its not send head things and error is poping up and that's why token is not appearing in the postman const jwt = require("jsonwebtoken"); require('dotenv').config();
function jwtGenerator(user_id){
const payload ={
user: user_id
}
return jwt.sign(payload, process.env.jwtSecret, {expiresIn: "1hr"});
}
module.exports = jwtGenerator; `>
< ` Here is my server.js file where server is not running its running i think fine only problem is in other 2 files someting missing or something parameter is not going through
const express =require("express");
const app = express();
const cors = require("cors");
app.use(express.json());
app.use(cors());
app.use("/auth",require("./routes/jwtAuth"));
app.listen(5000, () => {
console.log("Server is runnong on port 5000 ");
}) ` >
Upvotes: 0
Views: 210
Reputation: 114
Cannot set headers after they are sent to the client I remember getting this error when I did multiple response on the same api controller. Try checking that.
Upvotes: 0