sheppard
sheppard

Reputation: 67

How to call an external API from my API in Koa.js

I have an issue where I want to call an external API to verify a certain token coming from my frontend.

i.e

router.post('/api/verifyToken', async (ctx, next) => {
   router.post('https://external-site.com/verify').then((response) => {
       if (response.success) {  console.log('Do some stuff') };
   })
})

How would I go about doing this with koa?

Upvotes: 0

Views: 963

Answers (1)

n1md7
n1md7

Reputation: 3461

You misunderstood with the router itself.

In your router, you define a route where your clients can send HTTP requests and according to your business logic, you return the answers to them.

You can simply imagine router.post('/api/verifyToken' as an event listener. When a request comes in you run whatever is inside of it. It is not an HTTP client though.

If you want to send an external request you have to use an HTTP client for it.
There are a bunch of options:

And many others

One simple example how to do with Axios would be

import axios from 'axios';

router.post('/api/verifyToken', async (ctx, next) => {
   try{
     const response = await axios.post('https://external-site.com/verify');
     // Do your stuff here
     console.log(response.data);
     ctx.body = response.data;
   }catch(e){
     ctx.status = 422;
     ctx.body = e.message;
   }
})

Upvotes: 1

Related Questions