微信小程序websocket不能正常连接。
前端代码:
onLoad(options){
this.setData({
title:options.title
});
var that = this;
console.log("准备连接")
wx.connectSocket({
url:"ws://localhost:3000/chat",
success(){
console.log("成功")
},
fail(){
console.log("失败")
},
complete(){
console.log("完成");
}
});
wx.onSocketOpen(function(res){
socketOpen = true;
console.log("websocket连接");
});
wx.onSocketError(function(res){
console.log("未能正常连接")
})
}
用express-ws中间件写的后端websocket服务:
app.js:
var app = express();
var expressWs = require("express-ws")(app);
...
var webso = require("./routes/ws");
app.use("/chat",webso);
routes/ws.js:
var express = require('express');
var router = express.Router();
router.ws("/",function(ws,req){
console.log("来自weapp的websocket连接")
ws.on('message',function(msg){
ws.send('back from node');
})
});
module.exports=router;
然后微信小程序无法正常发起websocket请求:
asdebug.js:1 WebSocket connection to 'ws://localhost:3000/chat' failed: Connection closed before receiving a handshake response
两种情况
你是否在创建app时候是否添加APP ID,添加域名?
如果你是创建了APP ID,同时在建立小程序的同时添加了APP ID,那您需要去管理后台添加相应的域名
提示: 添加后重启你的开发工具再运行
如果是在无APP ID情况下测试,大部分是因为您的express-ws没有配置正确
可能是由于你本地的服务没有配置好