[ad_1]
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!
[ad_2]