打开后,我需要websocket发送请求。目前,websocket已成功打开,但之后将不会发送该请求。
const WebSocket = require("ws");
const request = require("request");
const querystring = require("querystring");
const dotenv = require('dotenv');
const fs = require("fs");
const uuid = require("uuid");
dotenv.config();
function initialize() {
var options = {
method: "POST",
url: process.env.URL,
headers: { "content-type": "application/x-www-form-urlencoded" },
body: querystring.stringify({
grant_type: "password",
username: process.env.USERNAME,
password: process.env.PASSWORD,
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET
})
};
return new Promise((resolve, reject) => {
request.post(options, (error, response, body) => {
if (error) {
reject(error);
} else {
resolve(JSON.parse(body));
}
})
})
}
var tokenInit = initialize();
tokenInit.then((result) => {
console.log("Getting Access_Token!");
process.env.ACCESS_TOKEN = result.access_token;
process.env.REFRESH_TOKEN = result.refresh_token;
console.log("Finished!");
console.log(`Your Access Token is: ${process.env.ACCESS_TOKEN}`);
})
.then(() => {
connect().then(server => {
id = "002dad7c-0359-4c86-aa66-48952712a452";
server.send(`{\"channel\": \"device.helix\", \"subscribe\": {\"deviceId\": \"${id}\"}}`, () => {
console.log("request sent");
});
})
.catch(err => {
console.log(err);
});
})
.catch((err) => {
console.log("Something went wrong");
console.log(err);
})
function connect() {
return new Promise(function (resolve, reject) {
var server = new WebSocket(`${process.env.WSS}${process.env.ACCESS_TOKEN}`);
server.onopen = function () {
resolve(server);
server.on("message", function incoming(data) {
d = JSON.parse(data);
console.log(data);
});
};
server.onerror = function (err) {
reject(err);
};
});
}
我希望获得发送请求的代码,该请求应返回成功消息。目前,我仅收到一条消息,说明已建立连接