简体   繁体   English

即使出现标题也无法在浏览器中设置Cookies

[英]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请求上设置withCredentialshttps://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使响应标头中存在cookie,浏览器也不会设置cookie - Browser doesn't set cookie even if it is present in response headers AJAX 无法在 CORS 请求后在浏览器上设置 Cookie。 Set-Cookie 标头仅存在于 FireFox 中,不存在于 Chrome 中 - AJAX fails to set Cookies on browser after CORS request. Set-Cookie header is present only in FireFox, not in Chrome 即使设置了header:null,也会显示导航标题 - Navigation header is shown even though header:null is set 即使资源选项卡中存在javascript,也无法将断点设置为脚本 - Unable to set breakpoint to script even though the javascript is present in the resource tab 即使存在请求的资源,也不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource even though it is present 即使将其加载到浏览器中,也无法使用Three.JS制作OBJ动画 - Can't animate OBJ using Three.JS even though it is loaded in browser Cookies 不会在浏览器中设置,但会在 postman 中设置 - Cookies won't set in browser but does in postman 无法在人偶中设置Cookie - Can't set the cookies in puppeteer Cookies 标头存在,但 Cookies 未存储在浏览器中 - Cookies headers are present but Cookies are not stored in browser 即使设置了 NODE_PATH,也无法在 Node 中导入全局 package? - Can't import global package in Node even though NODE_PATH is set?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM