我部署了一个next.js app,实现了会员注册功能,通过next.js API路由响应前台发来的请求,在本地环境下,发送会员注册请求成功,但是部署到vercel后出现500错误,我想分发后还要保存会员信息,请帮助我解决这个问题
// components/auths/SignUpModal.tsx
...
const onSubmitSignUp = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
const signUpBody = {
email,
lastname,
firstname,
password,
birthday: new Date(
`${birthYear}-${birthMonth!.replace('월', '')}-${birthDay}`
).toISOString(),
};
signupAPI(signUpBody);
} catch (e) {
console.log(e);
}
};
...
// lib/api/index.ts
import Axios from 'axios';
const axios = Axios.create({
baseURL: process.env.NEXT_PUBLIC_URL,
});
export default axios;
// lib/api/auth.ts
import axios from 'axios';
interface SignUpAPIBody {
email: string;
firstname: string;
lastname: string;
password: string;
birthday: string;
}
export const signupAPI = (body: SignUpAPIBody) => {
axios.post('api/auth/signup', body);
};
// pages/api/auth/signup.ts
import { NextApiRequest, NextApiResponse } from 'next';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import Data from '../../../lib/data';
import { StoredUserType } from '../../../types/user';
export default async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const { email, firstname, lastname, password, birthday } = req.body;
if (!email || !firstname || !lastname || !password || !birthday) {
res.statusCode = 400;
return res.send('필수 데이터가 없습니다.');
}
const userExist = Data.user.exist({ email });
if (userExist) {
res.statusCode = 409;
return res.send('이미 가입된 이메일입니다.');
}
const hashedPassword = bcrypt.hashSync(password, 8);
const users = Data.user.getList();
let userId;
if (users.length === 0) {
userId = 1;
} else {
userId = users[users.length - 1].id + 1;
}
const newUser: StoredUserType = {
id: userId,
email,
firstname,
lastname,
password: hashedPassword,
birthday,
profileImage: '/static/image/default_user_profile_image.jpg',
};
Data.user.write([...users, newUser]);
const token = jwt.sign(String(newUser.id), 'my_private_secret');
const expires = new Date(Date.now() + 60 * 60 * 24 * 1000 * 3);
res.setHeader(
'Set-Cookie',
`access_token=${token};path=/expires=${expires.toUTCString()};httponly`
);
res.statusCode = 200;
return res.send(newUser);
}
res.statusCode = 405;
return res.end();
};
// lib/data/user.ts
import { readFileSync, writeFileSync } from 'fs';
import { StoredUserType } from '../../types/user';
const getList = () => {
const usersBuffer = readFileSync('data/users.json');
const usersString = usersBuffer.toString();
if (!usersString) {
return [];
}
const users: StoredUserType[] = JSON.parse(usersString);
return users;
};
const exist = ({ email }: { email: string }) => {
const users = getList();
return users.some((user) => user.email === email);
};
const write = async (users: StoredUserType[]) => {
writeFileSync('data/users.json', JSON.stringify(users));
};
export default { getList, exist, write };
// data/users.json
Error: ENOENT: no such file or directory, open 'data/users.json'
at Object.openSync (node:fs:600:3)
at readFileSync (node:fs:468:35)
at getList (/var/task/.next/server/pages/api/auth/signup.js:31:67)
at Object.exist (/var/task/.next/server/pages/api/auth/signup.js:45:17)
at signup (/var/task/.next/server/pages/api/auth/signup.js:83:33)
at Object.apiResolver (/var/task/node_modules/next/dist/server/api-utils/node.js:372:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async NextNodeServer.runApi (/var/task/node_modules/next/dist/server/next-server.js:488:9)
at async Object.fn (/var/task/node_modules/next/dist/server/next-server.js:751:37)
at async Router.execute (/var/task/node_modules/next/dist/server/router.js:253:36) {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: 'data/users.json'
}
Error: ENOENT: no such file or directory, open 'data/users.json'
at Object.openSync (node:fs:600:3)
at readFileSync (node:fs:468:35)
at getList (/var/task/.next/server/pages/api/auth/signup.js:31:67)
at Object.exist (/var/task/.next/server/pages/api/auth/signup.js:45:17)
at signup (/var/task/.next/server/pages/api/auth/signup.js:83:33)
at Object.apiResolver (/var/task/node_modules/next/dist/server/api-utils/node.js:372:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async NextNodeServer.runApi (/var/task/node_modules/next/dist/server/next-server.js:488:9)
at async Object.fn (/var/task/node_modules/next/dist/server/next-server.js:751:37)
at async Router.execute (/var/task/node_modules/next/dist/server/router.js:253:36) {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: 'data/users.json'
}
RequestId: 161d1ce4-2d12-4a36-8197-8463b6a18e70 Error: Runtime exited with error: exit status 1
Runtime.ExitError
我试着用谷歌搜索,但不能解决这个问题...无论我怎么搜索5天,我找不到任何相关的文章,所以我寻求帮助...
1条答案
按热度按时间hc2pp10m1#
文件系统
fs
在Next.js无服务器函数中不可用。您必须使用外部数据库来保存任何数据。在本地开发时它可能工作,但在部署时肯定不行。