const request = (params, opts, success, fail, complete) => {
params = formatParams(params)
params.Action = firstLetterUpper(params.Action)
var defaultParams = _buildParams()
params = Object.assign(defaultParams, params)
var method = (opts.method || 'GET').toUpperCase()
var normalized = normalize(params)
var canonicalized = canonicalize(normalized)
var stringToSign = `${method}&${encode('/')}&${encode(canonicalized)}`
const key = 'u92uXpgg0jOuRf3wtd41Df1kxfqwAG' + '&'
var signature = crypto.HMAC(crypto.SHA1, stringToSign, key, {
asBase64: true
})
normalized.push(['Signature', encode(signature)])
const url = method === 'POST' ? `${'https://iot.cn-shanghai.aliyuncs.com'}/` : `${'https://iot.cn-shanghai.aliyuncs.com'}/?${canonicalize(normalized)}`
if (method === 'POST') {
opts.headers = opts.headers || {};
opts.headers['content-type'] = 'application/x-www-form-urlencoded'
opts.data = canonicalize(normalized)
}
wx.request({
url: url,
data: opts.data ? opts.data : {},
header: opts.headers,
method: method,
dataType: 'json',
responseType: 'text',
success: function(res) {
if (typeof success === 'function')
success(res)
else
console.log("success is not a function")
},
fail: function(res) {
if (typeof fail === 'function')
fail(res)
else
console.log("fail is not a function")
},
complete: function(res) {
if (typeof complete === 'function')
complete()
else
console.log("complete is not a function")
}
})
}
以上代码在云函数运行,提示wx is not defined,有没有朋友能帮我把这段代码该成在云函数里可以用的。
多谢!
感谢您的回复!
我采用如下代码可以正确收到服务器返回的数据,
axios({
url: url,
data: opts.data ? opts.data : {},
header: opts.headers,
method: 'POST',
dataType: 'json',
responseType: 'text'
}).then(res => {
console.log(res.data) //可以查询到正确的结果
}).catch(error => {console.log(error)})
但是还有两个问题,第一个是服务器返回的数据res.data怎么返回到主函数里呢?
主函数如下:
console.log('Start')
const resultValue = await queryDevicePropertyStatus("a1FGCXEvXEE", list.data[i].deviceid);
console.log(resultValue)
console.log('End')
async function queryDevicePropertyStatus(productKey, deviceName) {
const aliSdk = require("aliIot-sdk.js");
aliSdk.request({
Action: "QueryDevicePropertyStatus",
ProductKey: "a1FGCXEvXEE",
DeviceName: deviceName
}, { method: "POST"})}
第二个问题是,返回的数据怎么同步,1.651秒后才收到服务器返回数据,但是主函数已经执行完毕了,Start和End之间打印的输出是undefined,调试输出如下:
[info] 函数被触发,正在执行中...
index.js:69 Start
index.js:72 undefined
index.js:73 End
node.js:1 [info] 函数执行成功(耗时 1647ms) undefined
node.js:1 [info] 调用 本地 云函数 'timer' 完成 (耗时 1651ms)
aliIot-sdk.js:168 {"Data":{"List":{"PropertyStatusInfo":[{"Identifier":"CURR1","Value":"0000000
再次感谢!