最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cookies sent from backend but not set correctly on frontend - Stack Overflow

programmeradmin1浏览0评论

I'm running into this issue:

  • localhost:3000 (React App)
  • localhost:9000 (Nodejs Backend)

I was able to send the request from postman and receive the cookies there, however in the frontend when I check for the cookies in the browser there is nothing.

The cookies are not visible under the Application > Cookies tab.

The code I use for handing signups and sending the cookie:

// requirements
const User = require('../models/User');
const jwt = require('jsonwebtoken');

// handle errors
const handleErrors = (err) => {
    console.log(err.message, err.code);
    let errors = { first_name: '', last_name: '', email: '', password: '' };

    // duplicate error code
    if (err.code === 11000) {
        errors.email = 'That email is already registered';
        return errors;
    }

    // validation errors
    if (err.message.includes('User validation failed')) {
        Object.values(err.errors).forEach(({ properties }) => {
            errors[properties.path] = properties.message;
        });
    }
    return errors;
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({ id }, 'Dummy Secret', {
        expiresIn: maxAge
    });
}

// module exporting

module.exports.signup_post = async (req, res) => {
    const { first_name, last_name, email, password } = req.body;
    
    try {
        const user = await User.create({ first_name, last_name, email, password });
        const token = createToken(user._id);
        res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
        res.status(201).json({ user: user._id });
    }
    catch (err) {
        const errors = handleErrors(err);
        res.status(400).json({ errors });
    }
};

If anyone could guide me on what to do I'd be grateful

UPDATE: I did some testing and the results were as follows: when I ran this code in the main app.js on the backend and send a request from the front end, the cookies were still messed up, so it might very well be the frontend.

app.get('/set-cookies', (req, res) => {
    res.cookie('newUesr', false);
    res.cookie('isEmployee', true, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true});

    res.send('you got the cookies!');
});

app.get('/read-cookies', (req, res) => {
const 

});

But when I do it through my controllers in the previously shown code it gets stuck in set cookies as shown in this picture

I'm running into this issue:

  • localhost:3000 (React App)
  • localhost:9000 (Nodejs Backend)

I was able to send the request from postman and receive the cookies there, however in the frontend when I check for the cookies in the browser there is nothing.

The cookies are not visible under the Application > Cookies tab.

The code I use for handing signups and sending the cookie:

// requirements
const User = require('../models/User');
const jwt = require('jsonwebtoken');

// handle errors
const handleErrors = (err) => {
    console.log(err.message, err.code);
    let errors = { first_name: '', last_name: '', email: '', password: '' };

    // duplicate error code
    if (err.code === 11000) {
        errors.email = 'That email is already registered';
        return errors;
    }

    // validation errors
    if (err.message.includes('User validation failed')) {
        Object.values(err.errors).forEach(({ properties }) => {
            errors[properties.path] = properties.message;
        });
    }
    return errors;
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({ id }, 'Dummy Secret', {
        expiresIn: maxAge
    });
}

// module exporting

module.exports.signup_post = async (req, res) => {
    const { first_name, last_name, email, password } = req.body;
    
    try {
        const user = await User.create({ first_name, last_name, email, password });
        const token = createToken(user._id);
        res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
        res.status(201).json({ user: user._id });
    }
    catch (err) {
        const errors = handleErrors(err);
        res.status(400).json({ errors });
    }
};

If anyone could guide me on what to do I'd be grateful

UPDATE: I did some testing and the results were as follows: when I ran this code in the main app.js on the backend and send a request from the front end, the cookies were still messed up, so it might very well be the frontend.

app.get('/set-cookies', (req, res) => {
    res.cookie('newUesr', false);
    res.cookie('isEmployee', true, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true});

    res.send('you got the cookies!');
});

app.get('/read-cookies', (req, res) => {
const 

});

But when I do it through my controllers in the previously shown code it gets stuck in set cookies as shown in this picture

Share Improve this question edited Feb 8, 2022 at 22:57 Nomas asked Feb 8, 2022 at 15:48 NomasNomas 711 gold badge1 silver badge8 bronze badges 18
  • I've been looking around, googling, and so on and I feel like I might be missing a step in the front end, however I can't find anything to help :/ – Nomas Commented Feb 8, 2022 at 15:57
  • I don't believe you can access httponly cookies in react since they are on the server. – Sean Commented Feb 8, 2022 at 15:59
  • An HttpOnly cookie means that it's not available to scripting languages like JavaScript. – Vitaliy Rayets Commented Feb 8, 2022 at 15:59
  • In developer tab there's a network tab, if you select the DOC and refresh the page, you can see your domain there click it and if there's no cookie present then you have not sent the response back to the user properly. – BGPHiJACK Commented Feb 8, 2022 at 16:04
  • User should be offered a cookie when first creating it, then following refreshes user will offer up their cookie unless server wants to change it. – BGPHiJACK Commented Feb 8, 2022 at 16:05
 |  Show 13 more ments

2 Answers 2

Reset to default 6

I was able to solve the issue by doing those steps:

  1. Making sure the fetch request has the withCredntials: true and credentials: 'include', so the fetch request would be like this:
    fetch("http://localhost:9000/testAPI", {
                withCredntials: true,
                credentials: 'include'
    })

Keep in mind this is only working with GET requests not POST requests without the 2nd step.

  1. For POST requests being blocked by cors, just make sure you have this line in your backend after you've required cors of course app.use(cors({credentials: true, origin: true})); using * or http://localhost:3000 (regardless of port number) instead of true seems to give the error.

NOTE: According to @ikhvjs the withCredntials: true is not required, however I'm yet to try this so try at your own risk.

Thank you all for the help :D

Here's a helpful link for understanding httpOnly cookies and alternate methods. How to get HTTP-only cookie in React?

发布评论

评论列表(0)

  1. 暂无评论