美文网首页
nodeJS新建一个server

nodeJS新建一个server

作者: 小枫学幽默 | 来源:发表于2017-07-24 14:57 被阅读1105次

1、nodeJS新建一个server应用

//server.js

//引用node的http模块
var http=require('http');

//创建一个服务器并指定请求处理函数
http.createServer(function(req,res){
  //设置返回的请求状态 200位成功 和返回头部及文件编码
  res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
  //向客户端返回内容
  res.end('Hello world ! 我是node服务器的返回!');
})
//监听 8888 端口
.listen(8888);
console.log('服务器开启在:http://localhost:8888/');

命令行输入 node server.js

命令行

浏览器打开http://localhost:8888
运行结果:

image.png

这时候,我们会发现无论我们请求http://localhost:8888/index/http://localhost:8888/index.html/http://localhost:8888/index.png/等等等。。。服务器返回的都是我们在server.js里面res.end()里面定义的字符串。

也就是说,这时候建立的server,接受了所有的请求,都返回我们定义的字符串

2、nodeJS新建一个server应用,返回一个html

在当前目录新建 html.js 和 index.html

//====================>html.js
//引入http,模块
var http=require('http');
//引入url模块 解析请求的url
var url=require('url')
//引入IO文件模块 操作文件
var fs=require('fs')

//创建server 并指定服务器请求响应函数
http.createServer(function(req,res){
  var pathname=url.parse(req.url).pathname;
  if(pathname=='/index.html'){
    //请求 index.html 返回请求状态为200
    var data = fs.readFileSync('./index.html').toString();//读取文件内容并转换为字符串
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
    res.end(data);
  }else{
    console.log('hello world');
    //不是请求 index.html 返回请求状态为404
    res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
    res.end('hello world');
  }
})
//指定服务器监听的端口
.listen(8888);
console.log('服务器开启在:http://localhost:8888/');

//=======================>index.html
<!DOCTYPE html>
<html>
<head>
  <title>index</title>
</head>
<body>
我是读取文件后返回的html
</body>
</html>

````node html.js```

运行结果:

image.png
未完待续......

相关文章

网友评论

      本文标题:nodeJS新建一个server

      本文链接:https://www.haomeiwen.com/subject/iwvekxtx.html