NodeJs入門(二)
結合上篇文章
一:結合http與fs模組一起讀取資料夾中的檔案
在nodejs資料夾中建立day02資料夾,在day02資料夾中建立www資料夾與server.js檔案,在www資料夾中建立1.html與2.html,隨意寫上內容。
const http=require('http'); const fs=require('fs'); var server=http.createServer(function(req,res){ var file_name='./www'+req.url; //讀取檔案 fs.readFile(file_name,function(err,data){ if(err){ res.write('404'); }else{ res.write(data); } res.end(); }) }); server.listen(8080);
開啟window+r---cmd--node server.js

Image 1.png
在瀏覽器中開啟127.0.0.1:8080,依次輸入/1.html、/2.html

127.0.0.1:8080

127.0.0.1:8080/1.html

127.0.0.1:8080/2.html
二:http fs 接受前端傳過來的資料請求
要求: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