NuxtN
Nuxtβ€’3mo agoβ€’
5 replies
Garzec

server API endpoint 404 Not found

Given a basic contact page inside ./app/pages/contact.vue calling a submit event handler like this

// using the Nuxt UI form
async function onSubmit(event: FormSubmitEvent<Contact>) {
    await $fetch('/api/contact', {
        method: 'POST',
        body: event.data,
    });

    // clear form
    // add a success toast
}


For the API route I created a file at ./app/server/api/contact.post.ts with

// ... imports

const runtimeConfig = useRuntimeConfig()

type Contact = z.infer<typeof contactSchema>
const resend = new Resend(runtimeConfig.resendAPIKey)

export default defineEventHandler(async (event) => {
  try {
    const { customerRequestRecipientEmail } = runtimeConfig;

    if (!customerRequestRecipientEmail) {
      sendError(event, createError({
        statusCode: 400,
        statusMessage: '...',
      }))

      return
    }

    const body = await readBody<Contact>(event);

    const createEmailResponse = await resend.emails.send({
      from: body.mail,
      to: [customerRequestRecipientEmail],
      subject: '...',
      text: JSON.stringify(body) // good enough
    });

    if (!createEmailResponse.error) {
      return
    }

    sendError(event, createError({
      statusCode: 500,
      statusMessage: createEmailResponse.error.message,
    }))
  } catch (error) {
    // send 500 error
  }
});


Unfortunately I'm getting the warning

WARN [Vue Router warn]: No match found for location with path "/api/contact"

and response

{
  "error": true,
  "url": "http://localhost:3000/api/contact",
  "statusCode": 404,
  "statusMessage": "Page not found: /api/contact",
  "message": "Page not found: /api/contact",
  "data": {
    "path": "/api/contact"
  }
}


Do you know what's wrong or missing? Please let me know if my code is garbage I'm new to Nuxt πŸ™‚

Unfortunately the sandbox works ... dunno why https://stackblitz.com/edit/github-wb9hec5y?file=app%2Fserver%2Fapi%2Fcontact.post.ts
StackBlitz
A Vue.js project based on nuxt, vue and vue-router
Nuxt Server API Call Reproduction - StackBlitz
Was this page helpful?