【发布时间】:2020-07-18 05:23:09
【问题描述】:
编辑:添加了更多代码。
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({extended: false})
const {google} = require('googleapis');
const {PubSub} = require('@google-cloud/pubsub');
const iot = require('@google-cloud/iot');
const API_VERSION = 'v1';
const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
app.get('/', urlencodedParser, (req, res) => {
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).send(JSON.stringify({
data: OK
}))).catch(err => res.status(404).send('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
我有这个函数,我在 client 启动后调用:sendCom();
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, deviceId)
const binaryData = Buffer.from(command);
const request = { name: formattedName, binaryData: binaryData, };
client.sendCommandToDevice(request)
.then(responses => {
res.status(200).send(JSON.stringify({ data: OK })).end();
})
.catch(err => {
res.status(404).send('Could not send command. Is the device connected?').end();
});
}
我的问题是 sendCommandToDevice 可以完美执行,但是我得到了 catch error。 据我了解,这是因为在 .then 中结束了连接。
我查看了this,这就是我尝试过的,但我不确定我是否理解发生了什么。
【问题讨论】:
-
你正在使用
res.status....,而你的 lambda 得到responses。res来自哪里? -
@OmriAttiya 它在 app.get('/', urlencodedParser, (req, res) => {} 我上面贴的所有代码都在这里。
-
@Farrukh 是的,正如我所说,我认为这就是问题所在。但我不确定我应该在哪里或如何 .end() 它?
-
好吧,对于这种情况,您不需要调用 .end() 因为没有缓冲区来发送响应加上@OmriAttiya 关于 res.status 它应该是response.status ...
-
@Farrukh 我已经用更全面的代码更新了帖子,如果有帮助的话。我已经改变了你和OmriAttiya所说的。还是没有成功。
标签: node.js