Node.js上的服务器

Eng*_*ine 0 javascript node.js

我有一个运行静态index.html文件服务器的小脚本:

var http = require('http');
var fs =require('fs');


var server = http.createServer(function(req,res){
    console.log('request was made : '+req.url);
    res.writeHead(200,{'Content-Type':'text/html'});
    var myReadStream  = fs.createReadStream(__dirname +'/index.html','utf8');
    myReadStream.pipe(res);
});

server.listen(3000,'127.0.0.1');

console.log('listening to 3000');
Run Code Online (Sandbox Code Playgroud)

是否可以使用字符串代替“ localhost:3000”,例如“ MyPAGE”来调用html文件?

Que*_*tin 7

URL由以下几部分组成:

     foo://example.com:8042/over/there?name=ferret#nose
     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment
      |   _____________________|__
     / \ /                        \
     urn:example:animal:ferret:nose
Run Code Online (Sandbox Code Playgroud)

在您的示例中:

  • 该方案被省略,但是浏览器是隐式添加的,http://因为您是在地址栏中键入它。
  • 权限由主机名和端口组成
    • 主机名是 localhost
    • 该端口是 3000
  • 路径被省略,默认为 /
  • 其他所有内容均被省略,没有内容

为了使您使用,MyPage您需要:

  • 要使用的端口80(这是HTTP的默认端口,因此仅在使用默认端口时可以忽略它)
  • 您的浏览器将主机名解析MyPage为与localhost127.0.0.1在这种情况下)相同的IP地址

因此,您需要:

  1. 更改server.listen(3000,'127.0.0.1');server.listen(80, '127.0.0.1');。请记住,端口80是特权端口,因此您需要成为root / Administrator帐户才能在其中运行服务。
  2. 配置DNS或/etc/hosts使MyPage解析到正确的IP地址。