Why node.js requires an upgrade while trying to run an application on the localhost?

前端 未结 4 718
梦毁少年i
梦毁少年i 2020-12-20 11:53

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:

相关标签:
4条回答
  • 2020-12-20 12:31

    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.

    0 讨论(0)
  • 2020-12-20 12:49

    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;
    }
    
    0 讨论(0)
  • 2020-12-20 12:54

    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.

    0 讨论(0)
  • 2020-12-20 12:57

    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.

    0 讨论(0)
提交回复
热议问题