Next.js Discord

Discord Forum

405 Method Not Allowed

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
I'm using a page router and have dynamic API routing like this pages/api/[email].ts, it works fine in localhost, however when I try in production getting 405 method not allowed for POST request.

4 Replies

Asian black bearOP
export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
): Promise<void> {
    if (req.method !== 'POST') {
        return res.status(405).json({ error: 'Method Not Allowed' })
    }

    try {
        const { email } = req.query

        let responseData
        let errorMessage
        if (email === 'job') {
            const { name, email, number, resume, message, job } = req.body
            const { data, error } = await resend.emails.send({
                from: ENQUIRY_EMAIL,
                to: HR_EMAIL,
                subject: 'Resume received for Job Application',
                react: JobEmail({ name, email, number, message, job }),
                attachments: [
                    {
                        content: resume.content.split(',')[1],
                        filename: resume.fileName,
                    },
                ],
            })
            if (data?.id) {
                sendEmailToUser(name, email, HR_EMAIL)
            }
            responseData = data
            errorMessage = error
        } else if (email === 'ad-contact-email') {
            const { name, email, number, company, message } = req.body
            const { data, error } = await resend.emails.send({
                from: ENQUIRY_EMAIL,
                to: ENQUIRY_EMAIL,
                cc: SEO_EXPERT_EMAIL,
                subject: 'Ad Contact Form Enquiry',
                react: AdContactEmail({
                    name,
                    email,
                    number,
                    company,
                    message,
                }),
            })
            if (data?.id) {
                sendEmailToUser(name, email, ENQUIRY_EMAIL)
            }
            responseData = data
            errorMessage = error
        } else {
          ...  
        }

        ...
    } catch (error) {
        ...
    }
}
This is how I'm hitting the API

export const emailApi = async (
    api: string,
    data: InputFieldData
): Promise<Response> => {
    const response = await fetch(`/api/${api}`, {
        method: 'POST',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    })

    return response
}
"next": "^14.1.0",
export const config = {
    api: {
        externalResolver: true,
    },
}