[Vuejs]-Json response renders undefined in console, vue.js

0πŸ‘

βœ…

I see two issues, first the type of your response object, second the way you execute your request.

About the response object, the content of the response body is located in res.data but it seems your API also return a field data, so you might need to do res.data.data or update the body returned by your API.
Based on your example json response, the correct Typescript type would be:

export interface TestResponse {
  firtName: string
  lastName: string
}

export interface TestResponseRO {
  data: TestResponse[]
  metadata: string
}

If you use await, you do not need to use .then, you should instead do the following

async getTest() {
  try {
    const res = await request.get<TestResponseRO>("/v1/test");

    console.log(res.data) // Should display '{"data": [your array], "metadata": "none"}'

    return res.data 
  } catch (err) {
    console.error(err)
  }
}

If you still have an error, try to execute a request using curl or Postman to make sure your API is working well.

I also recommend you to use axios as HTTP client, it’s more flexible than request in my opinion.

Leave a comment