我正在開發一個使用 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;
希望這能解決您的問題:)