我尝试使用 NEXT JS 13 获取我的登录 api 端点,据说成功登录后会发出 access_token 和 refresh_token cookie,不幸的是浏览器中没有出现 cookie,但在我控制台日志的标头中显示正在设置cookie,这是一个错误还是什么? (它以前在 NEXT JS 12 中有效)
import React from 'react'
import TodoList from './TodoList'
const fetchSingle = async () => {
const res = await fetch
(`http://localhost:3000/auth/signin`, {
credentials: 'include',
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({ email: '[email protected]', password: '12345' })
})
try {
return res
} catch (error) {
return console.log('Error')
}
}
export default async function Todos() {
const response = await fetchSingle()
console.log(response)
return (
<div>
{/* @ts-ignore */}
<TodoList />
</div>
)
}
我不确定,但我认为您必须通过将“凭据”设置为“包含”来启用跨域 cookie:
fetch(url, {
cache: 'force-cache', // SSG (getStaticProps) // default
cache: 'no-store', // SSR (getServerSideProps)
next: { revalidate: 60 }, // ISR
credentials: 'include' // cross-origin cookies
})
我找到了答案,
在我的场景中,我在后端使用express,在CORS我需要添加以下内容
cors({ 来源:“http://localhost:3000”, 凭证:真实, })
在我的获取请求中,我需要添加选项 获取(API_HOST,{ 方法:“POST”, 标题:{ “内容类型”:“应用程序/json”, }, 正文:JSON.stringify(数据), 凭据:“包括”, })
现在浏览器允许从响应标头 Set-Cookie 保存 cookie