我正在开发一个使用 Google reCAPTCHA 的 React.js/Next.js 项目。我的前端似乎正在工作(我知道,因为我已经设置了打印语句),但后端在我的本地终端中给了我这个错误:
错误 - “srcappapirecaptcharoute.ts”中没有导出 HTTP 方法。为每个 HTTP 方法导出命名导出。
我的开发工具中也出现错误:
'POST http://localhost:3000/api/recaptcha 405(不允许的方法)'
我认为这与其他错误有关。
这是代码:
import { NextApiRequest, NextApiResponse } from 'next'; import express from 'express'; import cors from 'cors'; import bodyParser from 'body-parser'; import axios from 'axios'; const app = express(); app.use(cors()); app.use(bodyParser.json()); console.log('hi'); export async function postHandler(req: NextApiRequest, res: NextApiResponse){ if (req.method === 'POST') { const { token } = req.body; try { const response = await axios.post( `https://www.goog le.com/recaptcha/api/siteverifysecret=${process.env.NEXT_PUBLIC_RECAPTCHA_SECRET_KEY}&response=${token}` ); console.log('you made it here'); if (response.data.success) { res.status(200).json({ message: 'reCAPTCHA verification successful' }); } else { res.status(400).json({ message: 'reCAPTCHA verification failed' }); } } catch (err) { console.log(err); res.status(500).json({ message: 'Internal server error' }); } }; }
我尝试重命名该函数,将其导出为 const,并在文件末尾而不是在命名时导出。
P粉5059175902024-01-29 09:27:52
如果您使用的是 NextJS 13 App Router
,请使用以下代码:
文件:./app/api/recaptcha/route.ts
import { NextResponse } from 'next/server'; import axios from 'axios'; export async function POST(req: Request){ const { token } = req.body; try { const response = await axios.post(`https://www.google.com/recaptcha/api/siteverify?secret=${process.env.NEXT_PUBLIC_RECAPTCHA_SECRET_KEY}&response=${token}`,{},{headers: { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" }}); if (response.data.success) { return NextResponse.json({ message: 'reCAPTCHA verification successful' }) } else { return NextResponse.json({ message: 'reCAPTCHA verification failed' }) } } catch (err) { return NextResponse.json({ message: 'Internal server error' }) } }
如果您使用的是 NextJs 13 Page Router
,则使用:
文件:./pages/api/recaptcha.ts
import { NextApiRequest, NextApiResponse } from 'next'; const handler = async (req: NextApiRequest, res: NextApiResponse) => { if (req.method === 'POST') { const { token } = req.body; try { const response = await axios.post(`https://www.google.com/recaptcha/api/siteverify?secret=${process.env.NEXT_PUBLIC_RECAPTCHA_SECRET_KEY}&response=${token}`,{},{headers: { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" }}); if (response.data.success) { return res.status(200).json({ message: 'reCAPTCHA verification successful' }) } else { return res.status(400).json({ message: 'reCAPTCHA verification failed' }) } } catch (err) { return res.status(500).json({ message: 'Internal server error' }) } } else{ res.status(405).json({message: "Method Not Allowed"}) } }; export default handler;
希望这能解决您的问题:)