当前位置: 首页 > 工具软件 > node-static > 使用案例 >

node.js静态服务

单于飞鸣
2023-12-01

一、服务器区别

  • 对于其他的后端语言,比如php,wamp(apache—+mysql),java(tomcat)都有自己提供的服务器
  • node.js需要手写

二、书写语法

//1.引入http模块
const http=require('http')
//2. 创建服务
const server=http.createServer()
//3. 监听请求
server.on('request',(req,res)=>{
  res.end('hello bfy')  //客户端给用户返回的数据
})
//4.监听端口号  listen(port,ip,callback)
server.listen(3000,function(){
  console.log('node-server running at http:127.0.0.1:3000')
})

listen(port,ip,callback)三个参数:

  • port:端口号
  • ip:默认为1
  • callback:回调,用于提示

三、根据不同请求返还不同数据

1.引入模块
const http=require('http')
const path=require('path')
const fs=require('fs')
2.写监听

server.on(‘request’,(req,res)=>{

    //用户访问不同地址
  if(req.url === '/home'){
      fs.readFile(path.join(__dirname,'./views/v1.html'),'utf8',(err,data)=>{
        if(err) return console.log(err.message)
        res.end(data)
      })
  }
  else if(req.url === '/movie'){
      fs.readFile(path.join(__dirname,'./views/v2.html'),'utf8',(err,data)=>{
        if(err) return console.log(err.message)
        res.end(data)
      })
}else{res.end('404 not found')} 
})

server.listen(3000,function(){
  console.log('node-server running at http://127.0.0.1:3000')
})

四、静态服务的优化

对于静态服务,每请求一次要写一次监听十分不方便,可以优化,封装静态服务。

  • 封装时,对于不变的可以照搬,对于变化的部分作为参数传入即可
function fzfun(path,viewpath='./views',res){
    fs.readFile(path.join(__dirname,viewpath,path),'utf8',(err,data)=>{
        if(err) return console.log(err.message)
        res.end(data)
    })
}

传参数时传入访问地址path和res即可:

server.on('request',(req,res)=>{
	fzfun(req.url,res)
})

五、express开发框架

express时基于node.js平台,快速,开放,极简的web开发框架
语法类似node.js开发服务器

//1.q引入rxpress
const express=require('express')
//2.创建服务
const app=express()
//3. 监听请求
app.get('/',(req,res)=>{
    res.send('hello bfy')
})
app.get('/bfy',(req,res)=>{
    res.send('bfy')
})
app.post('api/post',(req,res)=>{
    res.send('post')
})
//4. 监听端口
app.listen(3000,'127.0.0.1',()=>{
    console.log('http://127.0.0.1:3000/')
})
  • res.send返回字符串,res.sendFile(绝对路径)返回页面
  • express的静态资源优化
app.use('/view',express.static(path.join(__dirname,'./view')))

use方法,关键字static管理静态资源文件夹

 类似资料: