所以我试图学习NextJs(TS),Prisma和MySQL,我试图在ReactJS中应用我的知识,但当我试图调用我的POST
时,我似乎遇到了一些麻烦。
这是我的目录x1c 0d1x
我得到这个错误
404 Not Found Not Found Not Found Not Found
Module not found: Can't resolve 'debug' in 'C:\Users\Student\Desktop\nextprisma\node_modules\follow-redirects'
Did you mean './debug'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (node_modules, C:\Users\Student\Desktop\nextprisma).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.
Import trace for requested module:
./node_modules/follow-redirects/debug.js
./node_modules/follow-redirects/index.js
./node_modules/axios/lib/adapters/http.js
./node_modules/axios/lib/adapters/adapters.js
./node_modules/axios/lib/axios.js
./node_modules/axios/index.js
./app/add/AddUser.tsx
字符串
这是我的表单。AddUser.tsx
const AddUser = () => {
const [data, setData] = useState({})
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
const response = await axios.post('/api/addUser', data);
if (response.status === 200) {
const newPost = response.data;
console.log('New post:', newPost);
} else {
console.error('Failed to create post');
}
} catch (error) {
console.error('Error:', error);
}
};
const handleChange = (e:any) => {
setData((prevData) => ({...prevData, [e.target.name]:e.target.value}))
}
return (
<form className='flex flex-col gap-2' onSubmit={handleSubmit}>
<div className='flex gap-2'>
<label>Email</label>
<input name="email" type="email" onChange={handleChange} />
</div>
<div className='flex gap-2'>
<label>Name</label>
<input name="name" type="name" onChange={handleChange} />
</div>
<button type="submit" className='border-2 bg-green-500 hover:bg-green-500/90 py-2 px-4'> Add </button>
</form>
)
}
export default AddUser
型
这是我的app/API/addUser.ts
export const addUser = async (req: NextApiRequest, res: NextResponse) => {
try {
const { name, email } = req.body;
const newPost = await prisma.user.create({
data: {
email,
name,
},
});
console.log(newPost);
} catch (error) {
console.log(error);
}
};
型
1条答案
按热度按时间prdp8dxp1#
在NextJS 13+中,目录结构发生了变化,您需要正确设置它以避免API路由的404错误。
就应该这样
字符串
route.ts
文件是/api
路由的不同路由的简单处理程序。文件应该是:route.ts
文件型
有了这两件事,你应该能够让你的API运行!只要确保你阅读api routes上的文档并遵循它。它涵盖了各种事情,如获取请求体,参数等。
祝你好运!