【发布时间】:2021-08-05 15:53:12
【问题描述】:
我正在使用 next.js 和strapi。 我正在尝试在我的下一个 js 前端和我的 Strapi 应用程序之间设置一个 httpOnly cookie。
cookie 由后端接收,但是当我尝试向后端发出请求时 - cookie 不存在。但是,当我使用邮递员时,cookie 集是存在的。
Strapi 应用:
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>
)
}
我尝试过的事情:
- 设置允许使用 cors 的特定域
- 将 api 调用移至 getServerSideProps 函数
- 从 next.js api 路由进行 api 调用
- 我尝试从普通的 html 文件发出请求,但它仍然无法正常工作,所以我现在假设这不是下一个 js 问题,因为无论如何它都是客户端。继承人的 HTML 代码不起作用 - 我得到了 cors 错误,然后当我没有时 - 我仍然没有得到 cookie 显示
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'
}
运气不好。
谁能告诉我发生了什么?我一直在寻找几个小时,但似乎没有任何工作
【问题讨论】:
标签: reactjs cookies next.js strapi httponly