nodejs快速搭个服务器

2021-08-05  本文已影响0人  沃尔德

不废话直接上代码,先来一个最简单的服务器: server.js如下:

const http = require("http");
const fs=require('fs');

var server=http.createServer(function(req,res){

  //http模块的 createServer()方法用于创建一个http服务:
  //参数: req,响应请求:
   //参数: res,返回应答:
  res.write("hello nodejs");
  res.end();
  //这一步在浏览器localhost:8898打开可以看到 hello nodejs(当然前提是node 运行一下文件);
  ----分割线---
  //但是这个服务器太low了,通常服务器都是可以返回文件的: 假设注释掉上面连行代码: 我们来看看req的用法:
  //假设我们在浏览器输出 localhost:8898/index.html   想当然我们是把这个页面返回给客户端;怎么做呢? 
  
  //req对象中,我们可以截取到 /index.html  

  var url=req.url // index.html  当然如果后面有参数也是可以截取到的
  
  //现在我们假设有一个www目录在 server.js的同级目录,www下新建 index.html ,页面内容自定义:
  
  //通常的想法是:
  if(url=='index.html'){
    fs.readFile("www/index.html",function(err,data){
      if(err){
        console.log("文件读取出错..")
      }else{
        res.write(data) //读取html内容页面,并返回给前端;
      }
      res.end()
    })
  }  if(url=="regester.html"){---codoe---}    //就像上面这样完成了一系列页面的请求; ---就如一个系统有数百个页面,这种方式就彻底over了,看下面方式

});

server.listen(8898)

一个服务器统一读文件和接口

const http = require("http");
const urlLib = require('url');
const fs = require('fs');
const querystring = require('querystring');

// console.log(querystring.parse("username=liuhf&password=123456"));

var server = http.createServer(function (req, res) {

    var obj = urlLib.parse(req.url, true);
    var path = obj.pathname;  //pathname;   host到? 前面之间的str

    var GET = {};  //测试get数据;
    var POST = {}; //测试post数据;

    if (path == '/favicon.ico') { return }   //chrome 浏览器会自动请求站点图标;
    GET = obj.query;

    var data_str = '';   //暂时存放简单数据;
    //作为一个服务器,最基本的具有 处理 文件请求 和 接口请求
    if (path.indexOf("api") < 0) {  //是文件请求  //这里只是简单的举一个例子;
        //文件服务器:
        fs.readFile("./www" + path, function (err, data) {      //相当于一个统一的映射到www目录;
            if (err) {
                console.log(err); 
            } else {
                res.write(data)
            }

            res.end();
          
        });


    } else {
        console.log("请求接口--")
        //接口请求:
        req.on("data", function (data) {   //仅对post数据有效;
            data_str += data;               //当post数据过大的时候,会分次传输送;
            console.log("post_data",data)
        }); 

        req.on("end", function (data) {    //end '事件' 并不是post独有,不管有没有post数据,都会进入这里;
            POST = querystring.parse(data_str)
            console.log("post提交--")
            console.log("GET:",GET);
            console.log("POST:",POST)
            res.end();
        });
    }


}).listen(8899);
上一篇下一篇

猜你喜欢

热点阅读