//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)三个参数:
const http=require('http')
const path=require('path')
const fs=require('fs')
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时基于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.sendFile(绝对路径)
返回页面app.use('/view',express.static(path.join(__dirname,'./view')))
use方法,关键字static管理静态资源文件夹