简体   繁体   中英

How do I start a server using nodejs?

I started learning nodejs and stopped at the lesson where the server is created, here is the code for this script:

var http = require('http'); // Import Node.js core module

var server = http.createServer(function (req, res) {   //create web server
    if (req.url == '/') { //check the URL of the current request
        
        // set response header
        res.writeHead(200, { 'Content-Type': 'text/html' }); 
        
        // set response content    
        res.write('<html><body><p>This is home Page.</p></body></html>');
        res.end();
    
    }
    else if (req.url == "/student") {
        
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<html><body><p>This is student Page.</p></body></html>');
        res.end();
    
    }
    else if (req.url == "/admin") {
        
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<html><body><p>This is admin Page.</p></body></html>');
        res.end();
    
    }
    else
        res.end('Invalid Request!');

});

server.listen(5000); //6 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

I experiment on a remote machine (google cloud virtual machine), run the script using node (I see a message in the console that the server is running) but if I go to the IP address through the browser (for example http://92.233.12.12:5000/ ) I don't I see the result, what am I doing wrong? did not find any additional information, everywhere in the lessons access through localhost:5000/ ...

res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();

You can also do the following:

res.end('<html><body><p>This is admin Page.</p></body></html>');

Please check if you are able to telnet the port 5000 for the remote server IP from your laptop terminal. It could be that a firewall is blocking the port for the outside access. If you want to check this on the server side you can login to the google machine and from the terminal of the server try curl http://localhost:5000 and if you see the response , then it should be the firewall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM