axios:TypeError: Cannot read properties of undefined

1、背景

从api获取数据,发现无法解析该json对象中的属性值。
以下是json数据的部分内容:

{“content”: { “[{“id” : 1 ,\n “title” : “第一篇博客” ,\n “content” : “这是一篇美食博客,广州早茶的红米肠是我最喜欢的美食之一”,\n “type” : “food”\n}]”}}

2、解决

(1)打印数据类型,发现是string

(2)转为object

this.axios.get('这里是一个api').then(res=>{
    
    
	//this.resultStr是我前面自己定义的变量resultStr,用于存放返回的string类型的JOSN数据
	this.resultStr = res.data.content; //res.data是从api返回的数据内容
	console.log(typeof this,resultStr); //string
	//要将string转为object
	this.resultJSON = JSON.parse(this.resultStr);
	console.log(typeof this,resultJSON); //object
	
	//这个时候就发现可以正常解析了。title是前面定义的resultJSON对象的属性
	console.log(this.resultJSON.pop().title); //这里我猜测,是用栈来存储的
})

控制台打印的 this.resultJSON:
在这里插入图片描述

3、同理,post请求

向服务器端传输数据的时候,要把object类型的json数据转为string类型

textStr = JSON.stringify({
    
    name: 'lisi', age:50});

猜你喜欢

转载自blog.csdn.net/qq_38432089/article/details/123882562
今日推荐