0
点赞
收藏
分享

微信扫一扫

http模块—http请求练习

谁知我新 03-31 19:30 阅读 1

题目要求:搭建如下http服务:

1.当浏览器向我们的服务器发送请求时,当请求类型是get请求,请求的url路径地址是/login。响应体结果是登录页面

 2.当浏览器向我们的服务器发送请求时,当请求类型是get请求,请求的url路径地址是/regist。响应体结果是注册页面

代码实现:

// 1.导入http模块
const http=require('http');
// 2.创建服务对象
const server=http.createServer((request,response)=>{
    // 在这里,我们从URL对象的多个属性中提取了pathname 属性,把提取到的pathname属性赋值给同名变量pathname。所以我们可以通过结构赋值的方式{}来提取request.url
    let {pathname}=new URL(request.url,'http://127.0.0.1');  //获取路径
    let {method}=request; //获取请求
    // 解决乱码
    response.setHeader('content-type',"text/html;charset=utf-8");
    if(method=='GET' && pathname=='/login'){
        response.end('登录');
    }else if(method=='GET' && pathname=='/regist'){
        response.end('注册');
    }else{
        response.end('404 NOT FOUND');
    }
});
// 3.监听端口,启动服务
server.listen(9000,()=>{
    console.log('服务已启动..端口9000监听中..');
})

当我们请求的路径为/login时显示的页面内容为:

当我们请求的路径为/regist时显示的页面内容为:

当我们请求的路径为其他时显示的页面内容为:

举报

相关推荐

0 条评论