我的cookie在部署到digitalocean作为App后,没有保存在React前端(由express后端发布)。
我们花了几天时间搜索整个stack overflow站点和google,但无法解释为什么我们的cookie可以正确保存在本地主机上,而不是在我们的开发环境中,这是通过digital ocean部署的。
我们可以在响应头中看到cookie,但它不会保存在浏览器存储中-无论是chrome还是safari。
后端
app.post('/api/cookie', function (req, res) {
//Base this on refresh token and make sure it is in hours
const userCookieAge = '1';
function setCookieAge(req) {
let hours = req
let age = hours * 60 * 60 * 1000;
return age
}
const AuthCookieSettings = {
domain: process.env.COOKIES_DOMAIN,
maxAge: setCookieAge(userCookieAge),
httpOnly: true,
sameSite: process.env.NODE_ENV === "production" ? 'none' : 'lax',
}
const UserCookieSettings = {
domain: process.env.COOKIES_DOMAIN,
maxAge: setCookieAge(userCookieAge),
httpOnly: true,
sameSite: 'none'
}
let key = req.body.key
let value = req.body.value
// Creates Secure Cookie with refresh token
res
.cookie( 'auth-cookie', JSON.stringify({ [key]: value,Settings: AuthCookieSettings}), AuthCookieSettings)
.cookie( 'user-cookie', JSON.stringify({ [key]: value,Settings:UserCookieSettings}), UserCookieSettings)
.json({status: 'succss', message: `Successfully created two cookies with key ${key} and value ${value}`});
});
工艺ENV
COOKIES_DOMAIN=".ondigitalocean.app"
CORS设置
const allowedOrigins = require('./allowedOrigins');
const corsOptions = {
credentials: true,
origin: (origin, callback) => {
console.log(`Request from Origin ${origin}`)
if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
console.log(`CORS request for Origin ${origin} granted`)
callback(null, true)
} else {
callback(new Error(`CORS request for Origin ${origin} denied!`));
}
},
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
optionsSuccessStatus: 200,
allowedHeaders: [
"Access-Control-Allow-Headers",
"Access-Control-Allow-Origin",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Credential",
"Origin",
"withCredentials",
"X-Requested-With",
"Content-Type",
"Accept",
"Authorization",
"X-HTTP-Method-Override",
"Set-Cookie",
"Cookie",
"Request"
],
}
module.exports = corsOptions;
前端
const [ key, setKey ] = useState('')
const [ value, setValue ] = useState('')
const url = '/api/cookie'
async function getCookie() {
const payload = {
key,
value
};
console.log(JSON.stringify(payload))
try {
const response = await axios.post(url,
JSON.stringify(payload),
{
headers: { 'Content-Type': 'application/json' },
withCredentials: true
}
);
const data = response?.data
if (data) {
console.log(`Response ${data.status}`)
}
} catch (error) {
console.error(error)
}
}
除了一些代码片段之外,您还可以在
前端:https://dev-frontend-f2yv7.ondigitalocean.app/后端:https://sea-lion-app-rm8kh.ondigitalocean.app/
cookie前端和后端的测试过程可以在https://dev-frontend-f2yv7.ondigitalocean.app/account/test下找到
只需键入键和值,然后单击“获取cookie”按钮。
我真的很感激你的帮助,因为我不知道我做错了什么。
谢谢你,马特
1条答案
按热度按时间4ioopgfo1#
对于任何人面临同样的问题与DigitalOcean应用程序服务.真实的的问题不是cookie设置,而是域设置。您必须在他们的应用程序服务中使用自己的自定义域名才能使Cookie发挥作用。在我的例子中,我使用了一个子域作为后端。server.intutec.io和前端intutec.io的常规域
我希望这能帮上忙...