Mr_Antivius
Mr_Antivius

Reputation: 693

Can't set Cookies in browser even though header is present

I was working on adding cookies to my project, full source here, but I ran into an issue where I can't set the cookies properly. I made a new api route that just creates a cookie and sends an object to the client.

server/routes/todo.routes.js

router.get('/todos', (req, res) => {
    res.cookie('mycookie', 'a_value')
    return res.send([{id:'1',isCompleted:false,text:'something'}])
})

If I call this api route directly, the browser renders the object and the cookie is set. The problem is when I call this api via AJAX from a rendered page, I still get the same response, but cookies aren't set. NOTE: I export the router and do app.use('/api', exported_object_here), so the URL is /api/todos.

shared/actions/todo.actions.js

export const getTodos = () => {
    return (dispatch) => {
        return fetch('/api/todos')
            .then(response => response.json())
            .then(todo => dispatch(_receiveTodos(todo)))
            .catch(err => dispatch(_errorHandler(err)));
    }
};

I have no idea why the browser would act differently in that situation, especially with something so simple. Do you all have any clue what could cause this?

Upvotes: 1

Views: 3832

Answers (1)

Mihai Potra
Mihai Potra

Reputation: 858

You need to set withCredentials on your XHR request (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials)

Upvotes: 1

Related Questions