![](/img/trans.png)
[英]How do I call a function at start in Expressjs/nodejs (Setup method)
[英]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.