Home > Mobile >  How sent cookies
How sent cookies

Time:12-23

I am trying to send cookies through the backend interface, and when I test it with the Postman, it is done as required. The problem is that cookies are not being sent in the browser.

Here is my code:

server.js

import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import  userRouter from "./routes/userRoutes.js";
import fileUpload from "express-fileupload";
dotenv.config();

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


//routes
app.use('/user' , userRouter)


const PORT = 5000;
mongoose.connect(process.env.MONGODB_URL , {useNewUrlParser : true , useUnifiedTopology : true})
    .then(() => app.listen(PORT , () => console.log(`Server is running on port : http://localhost:${PORT}`)))
    .catch((error) => console.log(error))

I sent cookies by login function:

export const login = async (req,res) => {
    try {
        const { email, password } = req.body;

        //check if empty
        if (!email) return res.status(400).json({ message: "Please write your Email." });
        if (!password) return res.status(400).json({ message: "Please write your Password" });


        //check email
        const user = await Users.findOne({ email });
        if (!user) return res.status(400).json({ message: "This email does not exist." });

        //check password
        const check_password = await bcrypt.compare(password, user.password);
        if (!check_password) return res.status(400).json({ message: "Password is incorrect." });

        const refresh_token = createRefreshToken({ id: user._id });
        const access_token = createAccessToken({ id: user._id });

        res.cookie('refreshtoken', refresh_token, {
            httpOnly:false,
            path: '/user/refresh_token',
            maxAge: 30*24*60*60*1000 // 30days
        });

        res.json({
            message: "Login success.",
            user,
            access_token
        });

    } catch (error) {
        return res.status(500).json({ message: error.message });
    }
}

And in the clientside I used redux:

export const login = (data) => async (dispatch) => {
    try {
        dispatch({ type: TYPES.NOTIFY, payload: { loading: true } });
        const res = await axios.post('http://localhost:5000/user/login',data);
        dispatch({
            type: TYPES.AUTH, payload: {
                token: res.data.access_token,
                user: res.data.user
            }
        });
        localStorage.setItem('token', res.data.access_token);
        dispatch({
            type: TYPES.NOTIFY,
            payload: {
                success: res.data.message
            }
        })

    } catch (error) {
        dispatch({
            type:TYPES.NOTIFY,
            payload:{
                error : error.response.data.message
            }
        })
    }
}

---------Edite---------

I used axios.defaults.withCredentials but issues still same :

export const login = (data) => async (dispatch) => {
try {
    dispatch({ type: TYPES.NOTIFY, payload: { loading: true } });
    const res = await axios.post('http://localhost:5000/user/login',data , axios.defaults.withCredentials = true);
    dispatch({
        type: TYPES.AUTH, payload: {
            token: res.data.access_token,
            user: res.data.user
        }
    });
    localStorage.setItem('token', res.data.access_token);
    dispatch({
        type: TYPES.NOTIFY,
        payload: {
            success: res.data.message
        }
    })

} catch (error) {
    dispatch({
        type:TYPES.NOTIFY,
        payload:{
            error : error.response.data.message
        }
    })
}

};

CodePudding user response:

In axios you have to enable the option

axios.defaults.withCredentials = true

You can see more details here in this post

CodePudding user response:

Solution 1

I also faced this issue. I removed all the cookies which are stored before. It worked for me.

Solution 2

Use setHeader function from request object

const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");

app.use(express.json());

app.use(cookieParser());

app.get("/", (req, res) => {
  res.setHeader("Set-Cookie", "name=langesh");

  res.send("hello");
});

app.get("/get-cookie", (req, res) => {
  res.send(req.cookies);
});

app.listen(4000);
  • Related