I'm working on a React.js/Next.js project using Google reCAPTCHA. My frontend seems to be working (I know that because I've set up the print statements), but the backend gives me this error in my local terminal:
Error - No HTTP method exported in 'srcappapirecaptcharoute.ts'. Export named exports for each HTTP method.
An error also occurred in my development tools:
'POST http://localhost:3000/api/recaptcha 405 (Method not allowed)'
I think this is related to other errors.
This is the code:
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' }); } }; }
I tried renaming the function, exporting it as const, and exporting it at the end of the file rather than at naming time.
If you are using NextJS 13
App Router
, please use the following code:File:
./app/api/recaptcha/route.ts
If you are using NextJs 13
Page Router
, then use:File:
./pages/api/recaptcha.ts
Hope this solves your problem :)