Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

498
Views
Next.js Cors: cómo llamar a mi API Next js desde el sitio externo

Tengo una próxima aplicación js y estoy tratando de llamar a la API desde un sitio externo usando javascript.

https://myapi.com/api/users

Llame a este punto final como el siguiente.

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

Esto arroja un error CORS.

Mi archivo API (/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) }) }) }

¿Algún consejo? ¡gracias!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Usa esto en su lugar:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!