调用/pages/api返回404错误,路径看似正确求排查方案
404错误排查:URL路径看似正确但POST请求失败
我搞不懂为什么明明URL路径看起来是对的,却一直收到404错误。
错误信息
FormSchema.tsx:49 POST http://localhost:3000/pages/api 404 (Not Found)
app-index.js:33 Failed to submit form: Error: HTTP error! status: 404 at onSubmit (FormSchema.tsx:60:15) at async eval (index.esm.mjs:2229:1)
项目代码结构
/ └── pages └── api └── route.ts
提交表单的Fetch函数代码
async function onSubmit(values: z.infer<typeof FormSchema>) { try { const response = await fetch('/pages/api', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(values), }); console.log('Response status:', response.status); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const result = await response.json(); console.log('Form submission result:', result); toast({ title: "Form submitted successfully!", description: ( <pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4"> <code className="text-white">{JSON.stringify(result, null, 2)}</code> </pre> ), }); } catch (error) { console.error("Failed to submit form:", error); toast({ title: "Error submitting form", description: "Please try again later.", }); } }
我检查过URL,但问题好像不在URL上,用Postman测试也不行。
解决方法
- 修正请求路径:Next.js的
pages/api目录是API路由的专属目录,最终的URL不会包含pages前缀。你的route.ts文件对应的正确请求路径是/api/route,把fetch里的路径改成这个即可。 - 确认API文件逻辑:确保
route.ts正确导出了POST请求处理逻辑,示例如下:export default function handler(req, res) { if (req.method === 'POST') { // 处理POST请求的业务逻辑 res.status(200).json({ message: "提交成功" }); } else { res.setHeader('Allow', ['POST']); res.status(405).end(`不支持${req.method}方法`); } } - 重启开发服务器:修改API路由文件后,有时候需要重启Next.js开发服务器才能让新路由生效。
内容的提问来源于stack exchange,提问作者342k
相关产品推荐
相关产品推荐

