DEV Community

kanishk soni
kanishk soni

Posted on

solve an error of node.js

hi 👋 everyone my name is Kanishk and am new to this community. i face an error at noed.js
this is my code

import express from "express";
import cors from "cors";
import userModel from "./model/user.js";
import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";
import cookieParser from "cookie-parser";
const app = express();

app.use(cors({ origin: true, credentials: true }));
app.use(express.json());
app.use(express.urlencoded({extended : true}));
app.use(cookieParser());


app.get("/", (req, res) => {
  // res.cookie("passkey",token )
  res.send("Done");
});

app.post("/register", (req,res,next)=>{

  bcrypt.genSalt(10,(err,salt) =>{
      bcrypt.hash(req.body.password , salt , async (err,hash)=>{
        let token  = jwt.sign("req.body.email" , "secret");

              let createusers = await userModel.create({
                  username:req.body.username,
                  email:req.body.email,
                  password: hash,
                  passkey:token,

              })

              res.cookie("token",token);
              res.redirect("/");
              next();
      })
  })

});

app.post("/login", async (req, res) => {
  try {
      const user = await usermodel.findOne({ email: req.body.email });
      if (!user) {
          console.log("User not found");
          return res.status(404).send("User not found");
      }

      // Compare the provided password with the hashed password from the database
      const passwordMatch = await bcrypt.compare(req.body.password, user.password);
      if (passwordMatch) {
          // Generate JWT token
          const token = jwt.sign({ email: user.email }, "secret");

          // Set the token in a cookie
          res.cookie("token", token); // Example cookie options, adjust as needed

          console.log("Login successful");
          return res.status(200).send("Login successful");
      } else {
          console.log("something went wrong");
          return res.status(401).send("something went wrong");
      }
  } catch (error) {
      console.error("Error:", error.message);
      return res.status(500).send("Internal Server Error");
  }
  res.redirect("/")
});

app.listen(5000, () => {
  console.log("Your server is hosted on port 5000");
});

Enter fullscreen mode Exit fullscreen mode

I want when a user registers a cookie is sent to him or her on its browser

Top comments (0)