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

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

json response renders undefined in console, vue.js

问题

以下是翻译好的内容:

  1. 我有一个简单的vue.js应用程序,我正在尝试使用typescript打印一些文本JSON响应如下
  2. {
  3. "data": [
  4. {
  5. "firstName": "Foo",
  6. "lastName": "Smith"
  7. },
  8. {
  9. "firstName": "Mike",
  10. "lastName": "vue"
  11. },
  12. {
  13. "firstName": "go",
  14. "lastName": "lang"
  15. }
  16. ],
  17. "metadata": "none"
  18. }
  19. typescript
  20. export interface TestResponse {
  21. firstName: string;
  22. lastName: string;
  23. }
  24. axios调用
  25. const request: AxiosInstance = axios.create({
  26. baseURL: url.baseUrl,
  27. headers: {
  28. 'content-type': 'application/json',
  29. },
  30. //params: {base64_encoded: 'true', fields: 'stdout'},
  31. });
  32. export const api = {
  33. async getTest() {
  34. try{
  35. return await request.get<TestResponse[]>("/v1/test")
  36. .then(res => {
  37. console.log("lastname " + res.data[0].lastName);
  38. return res.data
  39. })
  40. }catch (err) {
  41. console.log("error" + err);
  42. }
  43. },
  44. }
  45. 但是在这里它总是渲染为undefined。我尝试了TestResponse[]Array<TestResponse>但都无济于事。
  46. 这应该给我一个数组,但我得到了
  47. 无法读取undefined的属性(读取'data'
  48. export default {
  49. name: "Test",
  50. setup() {
  51. const firstName = ref('');
  52. const lastName = ref('');
  53. const submit = async () => {
  54. try {
  55. const response = await api.getTest()
  56. if (response != null) {
  57. firstName.value = response[0].firstName
  58. lastName.value = response[0].lastName
  59. console.log("I am a name " + response[0].lastName)
  60. }
  61. } catch (error) {
  62. console.log('获取响应时出错:', error)
  63. }
  64. }
  65. return {
  66. firstName,
  67. lastName,
  68. submit
  69. }
  70. },
  71. };
英文:

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

  1. {
  2. &quot;data&quot;: [
  3. {
  4. &quot;firstName&quot;: &quot;Foo&quot;,
  5. &quot;lastName&quot;: &quot;Smith&quot;
  6. },
  7. {
  8. &quot;firstName&quot;: &quot;Mike&quot;,
  9. &quot;lastName&quot;: &quot;vue&quot;
  10. },
  11. {
  12. &quot;firstName&quot;: &quot;go&quot;,
  13. &quot;lastName&quot;: &quot;lang&quot;
  14. }
  15. ],
  16. &quot;metadata&quot;: &quot;none&quot;
  17. }

typescript

  1. export interface TestResponse {
  2. firstName:string;
  3. lastName:string;
  4. }

axios call

  1. const request: AxiosInstance = axios.create({
  2. baseURL: url.baseUrl,
  3. headers: {
  4. &#39;content-type&#39;: &#39;application/json&#39;,
  5. },
  6. //params: {base64_encoded: &#39;true&#39;, fields: &#39;stdout&#39;},
  7. });
  8. export const api = {
  9. async getTest() {
  10. try{
  11. return await request.get&lt;TestResponse&gt;(&quot;/v1/test&quot;)
  12. .then(res =&gt; {
  13. console.log(&quot;lastname &quot; + res.data.lastName);
  14. return res.data
  15. })
  16. }catch (err) {
  17. console.log(&quot;error&quot; + err);
  18. }
  19. },
  20. }

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

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

  1. export default {
  2. name: &quot;Test&quot;,
  3. setup() {
  4. const firstName = ref(&#39;&#39;);
  5. const lastName = ref(&#39;&#39;);
  6. const submit = async () =&gt; {
  7. try {
  8. const response = await api.getTest()
  9. if (response != null) {
  10. firstName.value = response[0].data.firstName
  11. lastName.value = response[0].data.lastName
  12. console.log(&quot;I am a name &quot; + response.lastName)
  13. }
  14. } catch (error) {
  15. console.log(&#39;Error while getting the response:&#39;, error)
  16. }
  17. }
  18. return {
  19. firstName,
  20. lastName,
  21. submit
  22. }
  23. },
  24. };

答案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:

  1. export interface TestResponse {
  2. firstName: string
  3. lastName: string
  4. }
  5. export interface TestResponseRO {
  6. data: TestResponse[]
  7. metadata: string
  8. }

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

  1. async getTest() {
  2. try {
  3. const res = await request.get<TestResponseRO>("/v1/test");
  4. console.log(res.data) // Should display '{ "data": [your array], "metadata": "none"}'
  5. return res.data
  6. } catch (err) {
  7. console.error(err)
  8. }
  9. }

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:

  1. export interface TestResponse {
  2. firtName: string
  3. lastName: string
  4. }
  5. export interface TestResponseRO {
  6. data: TestResponse[]
  7. metadata: string
  8. }

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

  1. async getTest() {
  2. try {
  3. const res = await request.get&lt;TestResponseRO&gt;(&quot;/v1/test&quot;);
  4. console.log(res.data) // Should display &#39;{&quot;data&quot;: [your array], &quot;metadata&quot;: &quot;none&quot;}&#39;
  5. return res.data
  6. } catch (err) {
  7. console.error(err)
  8. }
  9. }

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:

确定