使用node创建一个简单服务器

第一种

创建server.js文件
需要nodejs的内置模块 http —做服务端请求 或者搭建服务器使用
equire 异步加载模块(nodejs的内置模块 自定义模块)

/*
node 
使用node  创建一个本地服务器
*/ 
const http=require('http');
//创建服务
//createServer()  创建服务
//request(请求) response(响应)
let app=http.createServer((req,res)=>{
    
    
   //简单的响应 
   //设置服务端编码
   res.writeHead(200,{
    
    "Content-Type":"text/html;charset=utf-8"});
   //给服务器端界面写出值 界面显示node服务器
   res.write("node服务器");
   //end() 终止当前服务
   res.end();
});
//监听端口
//listen()  监听端口
app.listen('8080','localhost',()=>{
    
    
    //服务端口监听成功  回调匿名函数
    console.log("http:localhost:8080");
});

写入执行命令node server
浏览器路径:
http:localhost:8080

第二种

创建urlserver.js文件
引入node url路径解析模块
get路径传值的 服务端针对get传值进行路径解析

const http=require("http");
const url=require("url");
//例如
//http://127.0.0.1/?id=10086&name=maodou
let app=http.createServer((req,res)=>{
    
    
    //req  请求头  url(请求的路径)  method(请求方式)
    let path=url.parse(req.url,true).query;
    console.log(path);//{ id: '10086', name: 'maodou' }
    let id=path.id;
    let name=path.name;
    console.log(id,name);
    res.writeHead(200,{
    
    "Content-Type":"text/html;charset=utf-8"});
    //界面显示url路径解析
    res.write("url路径解析");
    res.end();
});
app.listen(80,'127.0.0.1',()=>{
    
    
    console.log("http:127.0.0.1:80");
})

写入执行命令node urlserver
浏览器路径:
http:127.0.0.1:80

Guess you like

Origin blog.csdn.net/weixin_47863547/article/details/119323030