如何自己开发一个简易服务器

381 阅读1分钟

前言

以前学过的Nodejs全忘了,回过头来闲来无事来玩玩NodeJs,node.js的web程序不用放入web容器中运行,可以自己创建一个http服务器运行程序。需要使用http核心模块。

1.创建一个js文件里面放这段代码

const express = require('express')
const app = express()

app.use((request,response,next)=>{
    console.log('有人请求服务器1了');
    console.log('请求来自于',request.get('Host'));
    console.log('请求的地址',request.url);
    next()
})

app.get('/api/students',(request,response)=>{
    const students = [
        {id:'001',name:'tom',age:18},
        {id:'002',name:'jerry',age:19},
        {id:'003',name:'tony',age:120},
    ]
    response.send(students)
})

app.get('/api/cars',(request,response)=>{
    const cars = [
        {id:'001',name:'奔驰',price:199},
        {id:'002',name:'马自达',price:109},
        {id:'003',name:'捷达',price:120},
    ]
    response.send(cars)
})

app.get('/api/hobbys',(request,response)=>{
    const cars = [
        {id:'001',name:'篮球',time:'3h'},
        {id:'002',name:'音乐',time:'4h'},
        {id:'003',name:'电影',time:'2h'},
    ]
    response.send(cars)
})

app.listen(5000,(err)=>{
    if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students');
})

可以在浏览器通过http://localhost:5000访问服务器。

2.在需要数据的地方发请求就行了