解析get方式傳送的請求
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);