我正在用redux工具包在next js 13中开发一个jwt认证系统。我有一个Django后端,它正在与我的下一个js前端通信。问题出在下一个js的API页面和redux工具包之间的通信中,以设置用户登录。下面是我在API页面中的代码:
export async function POST(request) {
const body = await request.json();
const { email, password } = body;
const bodystring = JSON.stringify({
email,
password
});
console.log(`Posted data is: ${bodystring}`);
try {
const apiRes = await fetch(`${API_URL}/api/token/`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: bodystring
});
const data = await apiRes.json();
// console.log(`Data is ${data}`)
if (apiRes.status === 200) {
console.log("Login Succesful")
NextResponse.setHeader('Set-Cookie', [
cookie.serialize(
'access', data.access, {
httpOnly: true,
secure: false,
maxAge: 60 * 30,
sameSite: 'strict',
path: '/api/'
}
),
console.log("Access token set succesfully"),
cookie.serialize(
'refresh', data.refresh, {
httpOnly: true,
secure: false,
maxAge: 60 * 60 * 24,
sameSite: 'strict',
path: '/api/'
}
),
console.log("Refresh token sorted too"),
]);
return NextResponse.json({
// res: body
success: 'Logged in successfully',
status: 200,
});
}
} catch (error) {
}
}
字符串
然后这里是我的auth.js,当用户成功登录时,它应该调度状态:
export const login = (email, password) => async dispatch => {
const body = JSON.stringify({
email,
password
});
// alert(`body is ${body}`) //This alert is showing data hence it`s working
dispatch({
type: SET_AUTH_LOADING
});
try {
const res = await fetch('/auth/login/api', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: body
});
alert(`Response is ${res}`) //There is a problem here. Check the page api
if (res.status === 200) {
alert("Login Succesful")
dispatch({
type: LOGIN_SUCCESS
});
dispatch(load_user());
} else {
alert("Login Failed")
dispatch({
type: LOGIN_FAIL
});
}
} catch (error) {
dispatch({
type: LOGIN_FAIL
});
}
dispatch({
type: REMOVE_AUTH_LOADING
});
}
型
当程序运行时,auth.js发送一个警报Response is [object Response]
,然后我在控制台中得到错误error TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:261:61) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
。
2条答案
按热度按时间mklgxw1f1#
若要修复此错误,需要在返回NextResponse对象之前初始化该对象的headers属性。您可以通过使用NextRequest对象上的headers属性作为起点来完成此操作。例如,您可以执行以下操作:
字符串
t1qtbnec2#
在进行了几次试验之后,我发现了this教程,它解释了如何使用Next 13。我意识到错误来自于没有在响应中设置头。在做了一些修改之后,下面是我在
route.js
中的最终代码。字符串