今天继续昨天的开发过程,开始使用微信小程序官方软件写前端接收数据
因为我开发的是一个新闻类型的小程序,所以第一个新闻界面基本都是从数据库获取数据,所以使用了 GET 方法
先来看下我的第一版代码
wx.request({
url: 'http://127.0.0.1:5000/news',
method:'GET',
header:{
'content-type': 'application/x-www-form-urlencoded'
},
success:function(res){
var message = res.data[0]
console.log(message)
}
})
},
然后它就报错了。。。
错误为 404 错误,于是我发现是header的问题,于是进行了修改 :
header:{
'content-type': 'application/json'
},
结果还是报错,只不过换了一种!
image.png
通过搜索,发现是还是header的问题
但是有两种解决方法:
1.将type指定为json,去掉application。
2.content-type': 'application/text。
两种方法都可以使用
下面新的问题就来了,那么我怎么把这条新闻打到微信小程序的界面呢?
于是我在里面添加了一个setdata函数:
10$9~13E{GG6FP}KFPMC)H4.png这里面的self是一个很重要的点,我实在request函数外将self设置为了this
onLoad: function () {
var self = this
wx.request({
url: 'http://127.0.0.1:5000/news',
method:'GET',
data:{
},
header:{
'content-type': 'json'
},
success:function(res){
var message = res.data
console.log(message)
self.setData({
news_content:res.data.news_content,
news_title:res.data.news_title,
news_image:res.data.news_image
})
}
})
},
然后在page的data中我们进行设置:
Page({
data: {
news_title:'',
news_content:'',
news_image:'',
},
好了,然后我们切换到wxml里面进行一些实验试试看
<!--index.wxml-->
<view class="container">
{{news_content}}
</view>
3{QWK95G4PL0`LM3R3@O8AC.png
然后我就发现已经成功了,可以在微信小程序中使用了!(再次菜鸡式鸡冻
网友评论