03.服务器处理请求之GET

服务器处理请求之GET

1.创建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 <form method="get" action="http://localhost:8080/login" name="form1">
     用户名:<input type="text" id="user" name="user"><br/>
     密码:<input type="password" id="pswd" name="pswd"><br/>
     <input type="submit" value="登录">
 </form>
</body>
</html>

2.创建server.js

方式一:原生

const http=require("http");
http.createServer((req,res)=>{
    if(req.url.indexOf('?')!==-1){
        let arr=req.url.split('?');
        let infoGet={};
        //arr[0]-----/login
        //arr[1]-----user=tom&pswd=123
        let arr2=arr[1].split('&');
        //arr2=>['user=tom','pswd=123'];
        for(let i=0;i<arr2.length;i++){
            let arr3= arr2[i].split('=');
            infoGet[arr3[0]]=arr3[1];
        }
        res.end(JSON.stringify(infoGet));
    }else{
        res.end("404");
    }
}).listen(8080,function(){
    console.log("The server is running!")
});

方式二:使用querystring模块

const http=require("http");
const querystring=require("querystring");
http.createServer((req,res)=>{
    if(req.url.indexOf('?')!==-1){
        let arr=req.url.split('?');
        let result=querystring.parse(arr[1]);
        console.log(result);
        res.end('ok');

    }else{
        res.end("404");
    }
}).listen(3000,function(){
    console.log("The server is running!")
});

方式三:使用url模块

const http=require("http");
const urlBoss=require("url");
http.createServer((req,res)=>{
   let result=urlBoss.parse(req.url,true);
   //url模块的第二个参数设置为true表示对各个字段进行切片
   console.log(result);
   res.setHeader('Content-Type','text/plain;charset=utf-8');
   res.end(result.query.user+'密码:'+result.query.pswd);

}).listen(8080,function(){
    console.log("The server is running!")
});

3.启动node服务

node server.js

在这里插入图片描述

4.访问服务器端口

http://localhost:8080/login?user=%E5%BC%A0%E4%B8%89&pswd=123456

ont color=’#c7254e’>http://localhost:8080/login?user=%E5%BC%A0%E4%B8%89&pswd=123456

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值