英文:
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.
{
"data": [
{
"firstName": "Foo",
"lastName": "Smith"
},
{
"firstName": "Mike",
"lastName": "vue"
},
{
"firstName": "go",
"lastName": "lang"
}
],
"metadata": "none"
}
typescript
export interface TestResponse {
firstName:string;
lastName:string;
}
axios call
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.lastName);
return res.data
})
}catch (err) {
console.log("error" + err);
}
},
}
However here it always renders undefined. I tried to TestResponse[]
and Array<TestResponse>
with no avail.
This should be giving me an array but I get
Cannot read properties of undefined (reading '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].data.firstName
lastName.value = response[0].data.lastName
console.log("I am a name " + response.lastName)
}
} catch (error) {
console.log('Error while getting the response:', 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<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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论