node.js搭建web服务

1.确保已经安装node.js和npm

   注意:node.js不是JavaScript框架,而是js的运行环境

2.创建app.js,引入http模块,代码如下

var http=require('http');
var PORT=1234;
var app=http.createServer(function(req,res){
    res.writeHead(200,{'Content-type':'text/html'});
    res.write('<h1>hello world 2018.12.5<h1>');
    res.end();
})
app.listen(PORT,function(){
    console.log(('server is running at d%',PORT));
})

找到文件路径 ,终端运行 node app.js

在浏览器输入http://localhost:1234/

接着

修改代码,刷新浏览器,发现内容依然没有改变,因为为了确保性能,在启动服务时就将源代码加入到了内存中,可以通过supervisor来监听,实时改变

终端执行npm install supervisor -g

使node.js能让 /hello.html    /hi.html根据文件路径来返回内容

npm install supervisor -g

supervisor app.js

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

var PORT=1234;
var app=http.createServer(function(req,res){
    var path=__dirname+req.url;
  fs.readFile(path,function(err,data){
      if(err){
          res.end();
          return;
      }else{
          res.write(data.toString);
          res.end();
      }
})
})
app.listen(PORT,function(){
    console.log(('server is running at d%',PORT));
})

这种方式不方便 处理css javascript 等静态资源

可以使用node.js的框架express

首先使用npm install express安装  -g表示全局安装

接着写代码 

var http=require('http');

var express=require('express');

var PORT=1234;
var app=express();
app.use(express.static('.'));
app.listen(PORT,function(){
    console.log(('server is running at d%',PORT));
})
app.get('/hello',function(req,res){
res.send('hello');
})

执行 npm app.js

 

猜你喜欢

转载自blog.csdn.net/resilient/article/details/84844274
今日推荐