Reactjs HttpOnly cookie未发送到api
我正在使用next.js和strapi。 我正在尝试在我的下一个js前端和我的strapi应用程序之间设置一个httpOnly cookie cookie由后端接收,但是当我尝试向后端发出请求时,cookie不存在。然而,当我使用邮递员的饼干集是存在的 Strapi应用程序:Reactjs HttpOnly cookie未发送到api,reactjs,cookies,next.js,strapi,httponly,Reactjs,Cookies,Next.js,Strapi,Httponly,我正在使用next.js和strapi。 我正在尝试在我的下一个js前端和我的strapi应用程序之间设置一个httpOnly cookie cookie由后端接收,但是当我尝试向后端发出请求时,cookie不存在。然而,当我使用邮递员的饼干集是存在的 Strapi应用程序: const t = await ctx.cookies.get('mytest') // prints undefined with next js but works with postman console.l
const t = await ctx.cookies.get('mytest') // prints undefined with next js but works with postman
console.log(t);
ctx.cookies.set('mytest', '123', {
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 * 365,
secure: false,
})
next.js前端:
export default function Home(props: any) {
async function onClick() {
const options = {
method: 'GET',
'Access-Control-Allow-Credentials': true,
withCredenitals: true
}
const test = await fetch('http://localhost:1337/endpoint', options as any)
const res = await test.json()
}
return (
<div>
<div onClick={onClick}>
Make a fetch to the api
</div>
</div>
)
}
有人知道发生了什么事吗?我已经搜索了几个小时,但似乎什么都没用我最终解决了这个问题-问题是因为cookies没有保存到我的浏览器中 有两个问题:
const options = {
method: 'get',
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'include', // include, *same-origin, omit
withCredentials: true,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true,
"Access-Control-Allow-Origin": "http://127.0.0.1:1337/myapi"
},
}
const req = await fetch('http://127.0.0.1:1337/myapi', options)
const res = await req.json()
console.log(t);
ctx.cookies.set('mytest', '123', {
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 * 365,
secure: false,
})
ctx.response.header = {
...ctx.response.header,
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': ctx.request.headers.origin,
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,UPDATE,OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
}
credentials: 'include',
ctx.set('Access-Control-Allow-Origin', ctx.request.headers.origin)