代码改变世界程序员

解析get方式发送的请求

2018-11-29  本文已影响0人  Cherish丶任
http fs 接受前端传过来的数据请求(解析get方式发送的请求)

要求:get post ajax form 后台:转换成对象
form表单发送数据 转换对象格式
uname=Tom&upwd=123456 {uname:Tom,upwd:123456}

在day02文件夹中创建from.html文件与server1.js文件

from.html文件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <form action="http://localhost:8080" method="GET">
            <p>用户名:<input type="text" name="uname"></p>
            <p>密码:<input type="text" name="upwd"></p>
            <p><input type="submit" name="" id="" value="提交" /></p>
        </form>
    </body>
</html>
方法一:

server1.js

const http=require('http');
var server=http.createServer(function(req,res){
    GET=[]
    var arr=req.url.split('?');
    //console.log(arr);//['/','uname=Tom&upwd=123456']
    var arr1=arr[1].split('&');
    //console.log(arr1);//['uname=Tom','upwd=123456']
        //遍历数组
    for(var i=0;i<arr1.length;i++){
        var arr2 = arr1[i].split('=');
        //console.log(arr2);//["uname",'Tom'],['upwd','123456']
        GET[arr2[0]]=arr2[1];
        console.log(GET);//[uname:'Tom',upwd:'123456']
    }
})
server.listen(8080);
Image 5.png
方法二:

创建server2.js

//方法二:
const http=require('http');
const querystring=require('querystring');
var server=http.createServer(function(req,res){
    var GET=[]
    var arr=req.url.split('?');
    GET=querystring.parse(arr[1]);
    console.log(GET);
})
server.listen(8080);
Image 6.png

方法三

url模块
const http= require('http');
consr urls = require('url');
var server=http.createServer(function(req,res){
  var urlLis=urls.parse('http://www.baidu.com/index?uname=Tom&upwd=123456',true);
  console.log(urlLis);
  console.log(urlLis.query);//{uname:'Tom',upwd:'123456'}
});
server.listen(8080);
上一篇 下一篇

猜你喜欢

热点阅读