# web 接入 mqtt
安装:
npm i mqtt
客户端代码:
import * as mqtt from 'mqtt/dist/mqtt.min';
const clientId = 'emqx_vue3_' + Math.random().toString(16).substring(2, 8);
const username = '';
const password = '';
const host = location.host;
const client = mqtt.connect('ws://' + host + '/wsUrl', {
clientId,
username,
password,
});
client.on('connect', function () {
client.subscribe('presence', function (err) {
if (!err) {
client.publish('presence', 'Hello mqtt');
}
});
});
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString());
client.end();
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
vite 配置:
{
server: {
proxy: {
'^/wsUrl': {
target: 'ws:/127.0.0.1:8000',
changeOrigin: true,
ws: true,
rewrite: path => path.replace(/^\/wsUrl/, ''),
},
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12