Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

499
Visualizações
Next.js Cors- How to call my Next js API from the external site

I have a next js app and am trying to call the API from external site using javascript.

https://myapi.com/api/users

Call this endpoint like the below.

$.get('https://myapi.com/api/users').then()

This throws a CORS error.

My API file (/pages/api/users/index.js)

import Cors from 'cors'

// Initialize the cors middleware
const cors = initMiddleware(
  // You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
  Cors({
    // Only allow requests with GET, POST and OPTIONS
    methods: ['GET', 'POST', 'OPTIONS']
  })
)

export default async function handler(req, res) {
  // Run cors
  await cors(req, res)

  // Rest of the API logic
  res.json({ message: 'Hello Everyone!' })
}

function initMiddleware(middleware) {
  return (req, res) =>
    new Promise((resolve, reject) => {
      middleware(req, res, result => {
        if (result instanceof Error) {
          return reject(result)
        }
        return resolve(result)
      })
    })
}

Any advice? thank you!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use this instead:

 import Cors from 'cors'

    // Initializing the cors middleware
    const cors = Cors({
      methods: ['GET', 'HEAD'],
    })

    // Helper method to wait for a middleware to execute before continuing
    // And to throw an error when an error happens in a middleware
    function runMiddleware(req, res, fn) {
      return new Promise((resolve, reject) => {
        fn(req, res, (result) => {
          if (result instanceof Error) {
            return reject(result)
          }

          return resolve(result)
        })
      })
    }

    async function handler(req, res) {
      // Run the middleware
      await runMiddleware(req, res, cors)

      // Rest of the API logic
      res.json({ message: 'Hello Everyone!' })
    }

    export default handler
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda