JSON响应在控制台中显示为undefined,vue.js

huangapple go评论68阅读模式
英文:

json response renders undefined in console, vue.js

问题

以下是翻译好的内容:

我有一个简单的vue.js应用程序,我正在尝试使用typescript打印一些文本JSON响应如下

{
   "data": [
      {
         "firstName": "Foo",
         "lastName": "Smith"
      },
      {
         "firstName": "Mike",
         "lastName": "vue"
      },
      {
         "firstName": "go",
         "lastName": "lang"
      }
   ],
   "metadata": "none"
}

typescript

export interface TestResponse {
   firstName: string;
   lastName: string;
}

axios调用

const request: AxiosInstance = axios.create({
   baseURL: url.baseUrl,
   headers: {
      'content-type': 'application/json',
   },
   //params: {base64_encoded: 'true', fields: 'stdout'},
});

export const api = {

   async getTest() {
      try{
         return await request.get<TestResponse[]>("/v1/test")
            .then(res => {
               console.log("lastname " + res.data[0].lastName);
               return res.data
            })
      }catch (err) {
         console.log("error" + err);
      }
   },

}

但是在这里它总是渲染为undefined。我尝试了TestResponse[]Array<TestResponse>但都无济于事。

这应该给我一个数组,但我得到了

无法读取undefined的属性(读取'data'

export default {
   name: "Test",

   setup() {

      const firstName = ref('');
      const lastName = ref('');

      const submit = async () => {
         try {
            const response = await api.getTest()

            if (response != null) {
               firstName.value = response[0].firstName
               lastName.value = response[0].lastName
               console.log("I am a name " + response[0].lastName)
            }
         } catch (error) {
            console.log('获取响应时出错:', error)
         }
      }

      return {
         firstName,
         lastName,
         submit
      }

   },

};
英文:

I have a simple vue.js app where I am trying to print out some text with typescript. The json response looks like.

{
&quot;data&quot;: [
{
&quot;firstName&quot;: &quot;Foo&quot;,
&quot;lastName&quot;: &quot;Smith&quot;
},
{
&quot;firstName&quot;: &quot;Mike&quot;,
&quot;lastName&quot;: &quot;vue&quot;
},
{
&quot;firstName&quot;: &quot;go&quot;,
&quot;lastName&quot;: &quot;lang&quot;
}
],
&quot;metadata&quot;: &quot;none&quot;
}

typescript

export interface TestResponse {
firstName:string;
lastName:string;
}

axios call

const request: AxiosInstance = axios.create({
baseURL: url.baseUrl,
headers: {
&#39;content-type&#39;: &#39;application/json&#39;,
},
//params: {base64_encoded: &#39;true&#39;, fields: &#39;stdout&#39;},
});
export const api = {
async getTest() {
try{
return await request.get&lt;TestResponse&gt;(&quot;/v1/test&quot;)
.then(res =&gt; {
console.log(&quot;lastname &quot; + res.data.lastName);
return res.data
})
}catch (err) {
console.log(&quot;error&quot; + err);
}
},
}

However here it always renders undefined. I tried to TestResponse[] and Array&lt;TestResponse&gt; with no avail.

This should be giving me an array but I get

Cannot read properties of undefined (reading &#39;data&#39;)

export default {
name: &quot;Test&quot;,
setup() {
const firstName = ref(&#39;&#39;);
const lastName = ref(&#39;&#39;);
const submit = async () =&gt; {
try {
const response = await api.getTest()
if (response != null) {
firstName.value = response[0].data.firstName
lastName.value = response[0].data.lastName
console.log(&quot;I am a name &quot; + response.lastName)
}
} catch (error) {
console.log(&#39;Error while getting the response:&#39;, error)
}
}
return {
firstName,
lastName,
submit
}
},
};

答案1

得分: 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 returns 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 {
  firstName: 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 an HTTP client, it's more flexible than request in my opinion.

英文:

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&lt;TestResponseRO&gt;(&quot;/v1/test&quot;);

    console.log(res.data) // Should display &#39;{&quot;data&quot;: [your array], &quot;metadata&quot;: &quot;none&quot;}&#39;

    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.

huangapple
  • 本文由 发表于 2023年5月18日 03:37:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定