Returning the result of a query to the external API with Adonisjs

Asked

Viewed 806 times

-2

I am consuming an external API with Request in an application made with , to request is done normally and is returning the statusCode and body but I cannot return to my API.

I want to return the same value that comes from the external API in the same pattern without any treatment:

const Request = require('request');

class MyAppController {

  async index({ response, auth }) {

    Request('https://domain.com/v1/, function (error, res, body) {
      console.log(res.statusCode);
      console.log(body);
      return response.status(res.statusCode).json({ body });
    });
  }

}

module.exports = MyAppController

  • Note: in the excerpt spoke a quotation marks in the path of the URL, but this is not the problem

  • If a quote is missing fix.

1 answer

0

I noticed that in its code the index function is being called using async, but inside it, the await is not being used. Try to make the following change in your code.

const Request = require('request');

class MyAppController {

  async index({ response, auth }) {
    try {
        const res = await Request("https://domain.com/v1/");
        return response.status(res.statusCode).send(res.body);
    } catch (e) {
      return response.status(500).json({err: e });
    }
}

module.exports = MyAppController

Another way to do this is by using Axios. To install from the terminal, at the root of your project, the command is this:

npm install axios

The same code would look like this:

const axios = require('axios');

class MyAppController {

  async index({ response, auth }) {
    try {
        const res = await axios.get("https://domain.com/v1/");
        return response.status(res.status).send(res.data);
    } catch (e) {
      return response.status(500).json({err: e });
    }
}

module.exports = MyAppController

Browser other questions tagged

You are not signed in. Login or sign up in order to post.