nextjs-challenge / frontend / src / pages / api / invoice.ts
invoice.ts
Raw
import type { NextApiRequest, NextApiResponse } from 'next'
import fetch from 'node-fetch'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    let hostname = req.headers.host
    // make a POST request with the data from the frontend to the backend
    const response = await fetch('http://' + hostname + '/api', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(req.body),
    })
    // Filter out non-POST requests
    if (req.method !== 'POST') {
      res.status(405).send({ message: 'Only POST requests allowed' })
      return
    }
    // parse the response
    const data = await response.json()
    // return the data
    res.status(200).json(data)
  } catch (error) {
    // return any errors
    if (error instanceof Error) {
      res.status(500).json({ error: error.message })
    } else {
      res.status(500).json({ error: 'An unknown error occurred' })
    }
  }
}