Skip to content

How to use/import in /server/api ? #249

@Yves852

Description

@Yves852

Hello.

I'm trying to use nuxt-mail server-side with Nuxt but I can't figure out how to import it . Working as expected in client but I would prefer avoid it. Is the project allowing it?

Here is my basic test api:

// server/api/test-mail.js

// import { useMail } from "#imports"
// import useEmail from 'nuxt-mail'
import { useEmail } from 'nuxt-mail'

export default defineEventHandler(async (event) => {
  const mail = useMail()
  // const body: any = await readBody(event)
  // sanitize sanitize sanitize sanitize sanitize sanitize sanitize
  console.log('Test email')
  try {
      mail.send({
        config: 'contact',
        from: 'John Doe',
        subject: 'Test nuxt-mail',
        text: 'This is an incredible test message',
      })
  }
  catch(e) {
    console.error(e)  // [nuxt] [request error] [unhandled] [500] useMail is not defined
    throw createError({
      statusCode: 500,
    })
  }
})
// Client side
<script lang="ts" setup>
const { error, execute, status } = await useFetch((): string => '/api/test-mail', {
  immediate: false,
})

// Works
/*
const mail = useMail()
function send() {
  try {
    mail.send({
      from: 'John Doe',
      subject: 'Test nuxt-mail',
      text: 'This is an incredible test message',
    })
  }
  catch (e) {
    console.error(e)
  }
}
*/
</script>

<template>
  <div>
    <button @click="execute">
      Send email
    </button>
    <div>{{ status }}</div>
    <div v-if="error">
      {{ error }}
    </div>
  </div>
</template>

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions