先贴一下报错的截图
为了方便各位CSDN朋友搜索(也许不会),再复制一遍文字报错信息
[渲染层网络层错误] Failed to load image http://127.0.0.1:23911/__tmp__/HRgxyYghLaR7dc38ccd3f5ddbc65d97e8f4de30a3804.jpeg
the server responded with a status of 500 (HTTP/1.1 500 Internal Server Error)
From server 127.0.0.1(env: Windows,mp,1.06.2306020; lib: 3.3.3)
我自己开发用的微信小程序,本地数据库,接口编写用Node。出现这个错误是在获取数据库中用户头像的网络地址时出现的,贴一下JS代码
// 调用微信小程序选择媒体文件的接口
wx.chooseMedia({
count: 1, //文件数量
mediaType: ['image'], //媒体类型
sourceType: ['album', 'camera'], //文件来源(本地和相机)
camera: 'back', //反面相机
success: res => {
const tempFiles = res.tempFiles[0]
console.log(tempFiles.tempFilePath)
wx.request({
url: utils.baseUrl + '/api/avaChange',
method: 'POST',
data: {
avatarUrl: tempFiles.tempFilePath,
staffId: this.data.userInfo.staffId
},
header: {
'Content-type': 'application/x-www-form-urlencoded'
},
//上传成功后,把获取的图片地址传给页面变量(就是换头像之后,数据库记录后把新图片的地址传给页面,把新图片渲染到页面里)
success: res => {
const data = res.data
if (data.code === 0) {
this.setData({
avatarUrl: tempFiles.tempFilePath,
'userInfo.avatarUrl': tempFiles.tempFilePath
})
}
}
})
}
})
每次我清除缓存之后,重新获取数据库中的网络地址时会报这个错误,但是重新选择一遍图片,新打印出的网络地址也没问题,然后就渲染成功了新的图片。于是我推测是页面的路径数据在存储到数据库和从数据库中拿出数据的过程中出现的错误。而变量在存入数据库之前我打印了一下,是没有问题的,拿出来的时候就出问题了。
然后我去搜索的图片的数据库存储,发现我们最开始获取的图片网络地址是临时的,也就是说我们存变量取变量值的过程属于是刻舟求剑了……
于是我参考了这位大佬的办法
// 调用微信小程序选择媒体文件的接口
wx.chooseMedia({
count: 1, //文件数量
mediaType: ['image'], //媒体类型
sourceType: ['album', 'camera'], //文件来源(本地和相机)
camera: 'back', //反面相机
success: res => {
const tempFiles = res.tempFiles[0]
console.log(tempFiles)
//把文件的临时网络路径转二进制
let imgbase64 = 'data:image/png;base64,' + wx.getFileSystemManager().readFileSync(tempFiles.tempFilePath, "base64")
console.log(tempFiles.tempFilePath)
wx.request({
url: utils.baseUrl + '/api/avaChange',
method: 'POST',
data: {
avatarUrl: imgbase64,
staffId: this.data.userInfo.staffId
},
header: {
'Content-type': 'application/x-www-form-urlencoded'
},
success: res => {
const data = res.data
if (data.code === 0) {
this.setData({
avatarUrl: tempFiles.tempFilePath,
'userInfo.avatarUrl': tempFiles.tempFilePath
})
}
}
})
}
})
再按照大佬的提示,把用户头像的字段的数据类型改为longtext(结构里面->点击相应字段后面的修改,进入到下面的页面,在类型里选择后点击保存即可)
这两步然后编译就报错了哈哈哈哈哈哈哈哈(bushi)
SyntaxError: Unexpected end of JSON input
然后继续使用搜索引擎
说是json字符串转object出现的问题,我首先怀疑是因为我改变了用户头像数据改变引起的连锁反应。(这里是因为我的用户信息在页面间传递了,使用了JSON.stringify()和JSON.parse()函数)
主要的原因就是因为在将json转成Object的时候,有不是json字符串的字符存在,所以转换就报错了。 Unexpected end of JSON input :json输入异常结束的错误。
然后我在传递参数之前,对参数进行了这样的处理
wx.redirectTo({
url: '/pages/index/index?data=' + encodeURIComponent(JSON.stringify(data)),
})
在目标页面获取数据的时候:
if (options.data) {
let userInfo = JSON.parse(decodeURIComponent(options.data)).data
this.setData({
userInfo: userInfo
})
console.log(userInfo)
}
然后报错消失!再次把缓存清除,出现的数据也是正确的了!
题外话:
SyntaxError: Unexpected end of JSON input 这个错误也许是使用JSON.stringify()/JSON.parse()和encodeURIComponent()/decodeURIConponent()的时候,参数的格式出了问题。
我找错误原因的时候参考了这些文章(挑选了两个关键的):
【SyntaxError: Unexpected end of JSON input】json字符串转object出现的问题字符串encodeURIComponent(编码)/decodeURIComponent(解码)