How can I use one API route from within another one? #11210
-
I have a working API route (confirmed with postman) at "/api/auth/emailAvailable" I want to call this API route from another API route, "/api/auth/register", so I did this: handler.use(async (req, res) => {
axios.post(process.env.ROOT_URL + "/api/auth/emailAvailable", {
email: req.body.email || ' '
}).then(subRes => res.json(subRes)).catch(e => res.json(e)) For some reason the response is always either a 400 with error, or an empty object. I also get this message in the console
Any idea what could be wrong? |
Beta Was this translation helpful? Give feedback.
Answered by
timneutkens
Mar 20, 2020
Replies: 1 comment 1 reply
-
The way you've outlined with fetching /api/auth/emailAvailable actually slows down the endpoint, instead you can import the function that you were going to execute. Eg: // pages/api/auth/emailAvailable.js
export function emailAvailable(email) {
// Just an example
return db.find(email).length > 0
}
export default (req, res) => {
return res.json({ available: emailAvailable(req.body.email) })
} // pages/api/auth/register.js
import {emailAvailable} from './emailAvailable'
export default (req, res) => {
const available = emailAvailable(req.body.email)
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
timneutkens
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The way you've outlined with fetching /api/auth/emailAvailable actually slows down the endpoint, instead you can import the function that you were going to execute.
Eg: