所以我尝试创建一个代理端点来混淆真实的的后端。我的前端是NextJS项目,后端是Strapi应用程序。我正在设置用户注册。我有一个/app/api/auth/register/route.js
,它将从表单接收传入的请求,然后用相同的数据发出一个请求,稍微修改一下,然后对Strapi auth端点发出一个实际的注册请求。
一切似乎都很好:NextJS端点接收到请求,数据就在那里,数据被发送到Strapi,响应从Strapi返回,然后一切就安静地结束了……浏览器从NextJ获得500个错误响应,但没有任何错误记录。
我的主要问题是-这是你应该如何处理/app文件夹(req.json().then((data) =>
)传入数据的吗?我如何才能看到实际的错误?我怎么才能让它工作?
// /app/api/auth/register/route.js
import { NextResponse } from 'next/server';
const POST = async function (req) {
return req.json().then((data) => {
fetch(`${process.env.STRAPI_URL}/api/auth/local/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: data.email,
password: data.password,
// username: data.email, // commented out to trigger validation error
}),
})
.then((response) => {
console.log('The data', data);
response.json().then((respData) => {
console.log(respData);
if (response.ok) {
console.log('The success');
return NextResponse.json({ message: 'Success' });
} else {
console.log('The error');
return NextResponse.json({ error: 'something went wrong' }, { status: response.status });
}
});
})
.catch((error) => {
console.log('Something went terribly wrong');
return NextResponse.json({ error: 'something went wrong' }, { status: 500 });
});
});
};
export { POST };
// console logs:
strapi_commerce-nextjs-1 | The data { email: 'john@doe.com', password: 'doe' }
strapi_commerce-nextjs-1 | {
strapi_commerce-nextjs-1 | data: null,
strapi_commerce-nextjs-1 | error: {
strapi_commerce-nextjs-1 | status: 400,
strapi_commerce-nextjs-1 | name: 'ValidationError',
strapi_commerce-nextjs-1 | message: 'username is a required field',
strapi_commerce-nextjs-1 | details: { errors: [Array] }
strapi_commerce-nextjs-1 | }
strapi_commerce-nextjs-1 | }
strapi_commerce-nextjs-1 | The error
我的NextJs版本是13.4.1
1条答案
按热度按时间klh5stk11#
答案归https://www.reddit.com/user/Bohjio/。答案是确保所有的promise都从视图中返回。所以
return fetch(...
和return response.json().then(...