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);
来源: http://www.jianshu.com/p/895aee663b91