Node js (二)

过程的流程图

在这里插入图片描述

一、搭建服务器

app.js:

// 引入http模块(不需下载)
const http = require("http");
//读取文件(.html等的文件),就需要引入文件模块
const fs = require("fs");
//搭建服务器,并以常量的形式存储起来
const myServer = http.createServer(function (request,response) {
   
    console.log("请求来了!");  //有请求来时执行
    console.log(request.url);
    response.write("hello,welcome to panzhihua");
    response.end();   //响应完以后一定要结束(不然浏览器上看不见响应的内容)

    let pathName="";   //文件地址
    if (request.url == "/"){
   
        pathName="/index.html";
    }
    else {
   
        pathName="request.url";
    }
        //读取文件
    fs.readFile("day1/public/"+pathName,"utf-8",function (err,data) {
   
        if (!err){
   
            response.write(data);
            response.end();
        }
        else{
   
            console.log(err);
        }
    })

});
myServer.listen(9999);  //监听服务器

在这里插入图片描述
当需要在服务器中访问文件(public文件下的文件)时
在这里插入图片描述

二、服务器的配置

node js中一个文件就是一个模块

express模块

日志模块

网页标题头像模块

app.js:

// node.js中一个文件就是一个模块

//引用express模块
const  myexpress = require("express");
//引用path模块(内置模块)
const path = require("path");
//引用日志模块
const  logger = require("morgan");
//引用favicon 模块
const favicon = require('serve-favicon');
//引用post提交方式的对应模块   获取post提交的数据
const bodyParser=require("body-parser");
//引用userRouter.js
const userRouter = require("./router/userRouter");

const app = myexpress();

//定义日志和输出级别  必须放在静态资源代码前
app.use(logger('dev'));  //dev:环境的依赖
//定义网页图标
app.use(favicon(__dirname +'/public/favicon.ico'));
//配置静态资源的路径  默认返回index.html页面
app.use(myexpress.static(path.join(__dirname,"publ
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值