繁体   English   中英

如何使用 nodejs 启动服务器?

[英]How do I start a server using nodejs?

我开始学习 nodejs 并在创建服务器的课程中停止,这是此脚本的代码:

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..')

我在远程机器(谷歌云虚拟机)上进行实验,使用 node 运行脚本(我在控制台中看到服务器正在运行的消息)但是如果我通过浏览器访问 IP 地址(例如http:// 92.233.12.12:5000/ ) 我没有看到结果,我做错了什么? 没有找到任何额外的信息,在课程中到处都是通过localhost:5000/访问...

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

您还可以执行以下操作:

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

请检查您是否能够从您的笔记本电脑终端 telnet 远程服务器 IP 的端口 5000。 可能是防火墙阻止了外部访问的端口。 如果你想在服务器端检查这个,你可以登录谷歌机器并从服务器的终端尝试 curl http://localhost:5000 ,如果你看到响应,那么它应该是防火墙。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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