unable to verify nodes.js (mern) cookie jwt token

13 Views Asked by At

I was creating a MERN project , in which i am setting a cookie by sending request to the backend route from frontend and its working as backend is generating a token and saving it the browser cookie . But when i am sending req to backend to verify the cookie then its consoling that req.cookies.token is undefined . Here is my Frontend code :

const handleOperations = async (field) => {
    try {
      const res = await axios.post(
        `${BASE_URL}/cards/operation`,
        {
          field,
        },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      // console.log(res);
      if (res) {
        return res;
      }
      console.log("Not fetched");
    } catch (error) {
      console.log(error);
    }
  };

Here is my Backend code :

export const operations = async (req, res) => {
  const token = req.cookies.token;
  console.log(token);
  const { field } = req.body;
  try {
    if (!token) {
      return res.status(200).json({ message: "missing field token" });
    }
    const response = await operationModel.findOne({ token });
    if (response) {
      if (field === "edit" && response.editRemain === true) {
        await operationModel.findByIdAndUpdate(
          { _id: response._id },
          { editRemain: false }
        );
        res.status(200).json({ edit: "Allow Edit" });
      } else if (field === "delete" && response.deleteRemain === true) {
        await operationModel.findByIdAndUpdate(
          { _id: response._id },
          { deleteRemain: false }
        );
        res.status(200).json({ delete: "Allow Delete" });
      } else {
        res.status(200).json({ message: "NO" });
      }
    } else {
      if (field === "edit") {
        await operationModel.create({
          token,
          editRemain: false,
        });
        res.status(200).json({ message: "Created" });
      } else if (field === "delete") {
        await operationModel.create({
          token,
          deleteRemain: false,
        });
        res.status(200).json({ message: "Created" });
      }
    }
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
};

Here is the error : enter image description here

i ahve used the cookie-parser also ,

const app = express();

app.use(express.json());
app.use(cors({
    origin : "http://localhost:3000" ,
    credentials : true
}));
app.use(cookieParser());


app.use(bodyParser.json({extended : true}));
app.use(bodyParser.urlencoded({extended : true}));
0

There are 0 best solutions below