[英]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. 我当时正在努力向我的项目中添加cookie, 这里有完整的源代码,但是遇到了无法正确设置cookie的问题。 I made a new api route that just creates a cookie and sends an object to the client.
我做了一个新的api路由,它只创建一个cookie并将一个对象发送给客户端。
server/routes/todo.routes.js 服务器/路由/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. 如果我直接调用此api路由,则浏览器将呈现该对象,并设置cookie。 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.
问题是,当我从渲染页面通过AJAX调用此api时,我仍然得到相同的响应,但是未设置cookie。 NOTE: I export the router and do app.use('/api', exported_object_here), so the URL is /api/todos.
注意:我导出路由器并执行app.use('/ api',exported_object_here),因此URL为/ api / todos。
shared/actions/todo.actions.js 共享/动作/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?
你们都有什么线索可能导致这种情况吗?
您需要在XHR请求上设置withCredentials
( https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.