Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics Deeper into Routing with Express Redirects

Shehan Dissanayake
Shehan Dissanayake
19,119 Points

Why do we use res.cookie() instead of req.cookie() when creating the cookie?

Does the server send the cookie from the server to browser? Why can't we use req.cookie() as the cookie is saved when the client is sending the request to the server?

1 Answer

Mike Schaming
Mike Schaming
13,925 Points

Hi Shehan,

Take this code snippet for example:

app.post('/hello', (req, res) => { res.cookie('username', req.body.username); //set cookie on client to input on username res.redirect('/'); });

When the server we set up receives a POST request, we have programmed the server to respond with res.cookie to set a cookie on the client called username.

As the server we are responding, so we want to use the Response object and its methods.

Hope this helps!