nodeJS新建一个server

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
未完待续......
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容