When I try to run my node.js application on a localhost server, it does not run and demands a required upgrade. I have tried to run the code but I get the following error:
Do not open a client HTML file as a localhost URL but open the file directly.
After running your web-socket server,
localhost:[port]/client.html
-> you will get the message "upgrade required".
file:///[folder]/client.html
-> you can see your HTML file.
because you don't have any web-server with a web-socket or you did not configure your web server for your web-socket. So, you should use your file system.
The easiest way is to use right click on the client file and open it with your favorite browser.
You need to combine your WebSocket based server and static html generator Express. For example
var express = require('express')
var expressWs = require('express-ws')
var app = express()
expressWs(app)
app.ws('/echo', (ws, req) => {
ws.on('connection', function (connection) {
//...
})
ws.on('close', function () {
//...
})
})
app.use(express.static('public'))
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
In client code
var ws = new WebSocket('ws://localhost:3000/echo');
ws.onmessage=function(event){
document.getElementById("result").value=event.data;
}
Upgrade Required
is a reference to the header that is sent when establishing a WebSocket connection between a client (i.e. the browser) and the server.
Like @Prinzhorn stated in his comment, you need a client application that connects to your WebSockets server, which could be a static html page. I recommend you reading this introduction to websockets to understand better how WebSockets work.
The issue is that your web socket server is running on port 80, so when you open the html template using your browser, you are actually opening the web socket server. This is because web pages opening in the browser default to using port 80.
To fix this set your web socket server's port to something else like 3000.
ws = new WebSocketServer({port: 3000})
Then when you open the page in the browser it will open the actual html page instead of the web socket server.