前面几篇都在复习nodejs创建HTTP服务器的若干知识点,本篇将使用原生AJAX和nodejs的HTTP服务器配合写几个DEMO,加深运用理解,也方便时间长回顾备查,客户端使用file
访问协议,服务端代码写在app.js中,客户端代码写在index.html中,所有demo均亲测可用。
表单submit提交数据
1//app.js
2const http = require( "http" );
3const queryString = require( "querystring" );
4let app = http.createServer( function ( req, res ) {
5 if( req.url !== "/favicon.ico" ){
6 let postData = "";
7 // 监听ajax提交时请求对象req的data事件,由于发送的数据是分片段给来,所以每接收到一段数据dataChunk就会触发data事件,
8 req.on( "data", function ( postDataChunk ) {
9 postData += decodeURIComponent( postDataChunk );
10 } )
11 req.on( "end", function () {
12 try{
13 res.setHeader( "Content-Type", "application/json;charset=utf-8" );
14 res.write( "你填写的名字是:" + queryString.parse( postData ).name + ";" );
15 res.write( "你填写的年龄是:" + queryString.parse( postData ).age + ";" );
16 res.write( "你填写的兴趣1是:" + queryString.parse( postData ).interests[0] + ";" );
17 res.write( "你填写的兴趣2是:" + queryString.parse( postData ).interests[1] + ";" );
18 res.write( "你填写的兴趣3是:" + queryString.parse( postData ).interests[2] + "。" );
19 }catch( e ){
20 console.log( e );
21 }
22 res.end();
23 } )
24 }
25} ).listen( 1335, ()=>{ console.log( "service is running at port 1335." ); } )
26
27
28//index.html
29<form action="http://127.0.0.1:1335" method="POST">
30 <input type="text" name="name">
31 <input type="text" name="age">
32 <input type="checkbox" name="interests" value="敲代码">敲代码
33 <input type="checkbox" name="interests" value="玩PS4">玩PS4
34 <input type="checkbox" name="interests" value="看书">看书
35 <input type="submit" value="提交">
36</form>
表单ajax提交数据
1// app.js
2const http = require( "http" );
3let app = http.createServer( function ( req, res ) {
4 if( req.url !== "favicon.ico" ){
5 try{
6 let reqData = "";
7 req.on( "data", function ( dataChunk ) {
8 reqData += decodeURIComponent( dataChunk );
9 } )
10 req.on( "end", function () {
11 res.setHeader( "Content-Type", "application/json;charset=utf-8" );
12 res.setHeader( "Access-Control-Allow-Origin", "*" );
13 res.write( reqData );
14 res.end();
15 } )
16 }catch( e ){
17 console.log( e );
18 }
19 }
20} ).listen( 1338, ()=>{ console.log( "service is running at port 1338." ); } )
21
22// index.html
23<body>
24 <form action="http://127.0.0.1:1338" method="POST" id="formData">
25 <input type="text" name="name">
26 <input type="text" name="age">
27 <input type="checkbox" name="interests" value="敲代码">敲代码
28 <input type="checkbox" name="interests" value="玩PS4">玩PS4
29 <input type="checkbox" name="interests" value="看书">看书
30 <input type="button" id="subBtn" value="提交">
31 </form>
32</body>
33let subBtn = document.getElementById( "subBtn" );
34subBtn.onclick = function( e ){
35 let form = document.querySelector( "#formData" );
36 let formData = new FormData( form );
37 let xhr = new XMLHttpRequest();
38 xhr.open( "POST", form.action );
39 xhr.setRequestHeader( "Content-Type", "multipart/form-data");
40 xhr.onreadystatechange = function () {
41 if( xhr.readyState === 4 ){
42 if( (xhr.status >= 200 && xhr.status < 300) || (xhr.status === 304) ){
43 let resData = xhr.response;
44 console.log( resData );
45 }
46 }else {
47 console.log( xhr.readyState );
48 console.log( "请求发送中..." );
49 }
50 }
51 xhr.send( formData );
52}
ajax的无参GET请求
1// app.js
2const http = require( "http" );
3let app = http.createServer( function ( req, res ) {
4 if( req.url !== "/favicon.ico" ){
5 try{
6 let resData = {name: "nitx", age: 31};
7 res.setHeader( "Content-Type", "application/json;charset=utf-8" );
8 // 设置跨域
9 res.setHeader( "Access-Control-Allow-Origin", "*" );
10 res.write( JSON.stringify( resData ) );
11 res.end();
12 }catch( e ){
13 console.log( e );
14 }
15 }
16} ).listen( 1336, ()=>{ console.log( "service is running at port 1336." ); } )
17
18//index.html
19<body>
20 <button type="button" id="btn">GET请求获取响应数据</button>
21 <div id="div"></div>
22</body>
23let btn = document.getElementById( "btn" );
24btn.onclick = function ( e ) {
25 let xhr = new XMLHttpRequest();
26 xhr.open( "GET", "http://127.0.0.1:1336" );
27 // 设置xhr对象的responseType属性值为json时,浏览器就会自动对返回数据调用JSON.parse()方法。该属性值默认是text
28 xhr.responseType = "json";
29 // xhr对象的onreadystatechange属性指向一个监听函数,当readystate属性变化时执行
30 xhr.onreadystatechange = function () {
31 if( xhr.readyState === 4 ){
32 if( (xhr.status >= 200 && xhr.status <300) || (xhr.status === 304) ){
33 let resData = xhr.response;
34 document.getElementById( "div" ).innerHTML = resData.name;
35 }else {
36 console.log( xhr.statusText );
37 }
38 }else {
39 console.log( xhr.readyState );
40 console.log( "ajax请求中..." );
41 }
42 }
43 xhr.send( null );
44}
45
ajax的带参GET请求
1// app.js
2const http = require( "http" );
3const url = require( "url" );
4let app = http.createServer( function ( req, res ) {
5 if( req.url !== "favicon.ico" ){
6 try{
7 let decodeUrl = url.parse( decodeURIComponent( req.url ), true );
8 let query = decodeUrl.query;
9 res.setHeader( "Content-Type", "application/json;charset=utf-8" );
10 res.setHeader( "Access-Control-Allow-Origin", "*" );
11 res.write( JSON.stringify( query ) );
12 }catch( e ){
13 console.log( e );
14 }
15 res.end();
16 }
17} ).listen( 1337, ()=>{ console.log( "service is running at port 1337" ); } );
18
19// index.html
20<body>
21 <button type="button" id="btn">GET提交数据并获取响应数据</button>
22 <div id="div"></div>
23</body>
24let btn = document.getElementById( "btn" );
25btn.onclick = function ( e ) {
26 let xhr = new XMLHttpRequest();
27 xhr.open( "GET", "http://127.0.0.1:1337?name=nitx&age=31" );
28 xhr.responseType = "json";
29 xhr.onreadystatechange = function () {
30 if( xhr.readyState === 4 ){
31 if( (xhr.status >= 200 && xhr.status < 300) || ( xhr.status === 304 ) ){
32 let resData = xhr.response;
33 console.log( resData );
34 document.getElementById( "div" ).innerHTML = resData.name + ":" + resData.age;
35 }
36 }else {
37 console.log( xhr.readyState );
38 console.log( "ajax加载中..." );
39 }
40 };
41 xhr.send( null );
42}
43
ajax的POST传参请求
1// app.js
2const http = require( "http" );
3
4let app = http.createServer( function ( req, res ) {
5 if( req.url !== "/favicon.ico" ){
6 let reqData = "";
7 req.on( "data", function ( dataChunk ) {
8 reqData += decodeURIComponent( dataChunk );
9 } )
10 req.on( "end", function () {
11 try{
12 res.setHeader( "Content-type", "application/json;charset=utf-8" );
13 res.setHeader( "Access-Control-Allow-Origin", "*" );
14 res.write( reqData );
15 res.end();
16 }catch( e ){
17 console.log( e );
18 }
19 } )
20 }
21} ).listen( 1340, ()=>{ console.log( "service is running at port 1340." ); } )
22
23
24// index.html
25<body>
26 <button type="button" id="btn">POST请求</button>
27 <div id="div"></div>
28</body>
29let paramData = { a: 1, b: 2 };
30let btn = document.getElementById( "btn" );
31btn.onclick = function () {
32 let xhr = new XMLHttpRequest();
33 xhr.open( "POST", "http://127.0.0.1:1340" );
34 xhr.onreadystatechange = function () {
35 if( xhr.readyState === 4 ){
36 if( xhr.status === 200 ){
37 let resData = xhr.response;
38 console.log( JSON.parse( resData ) );
39 }
40 }else {
41 console.log( xhr.readyState );
42 console.log( "请求加载中..." );
43 }
44 }
45 xhr.send( JSON.stringify( paramData ) );
46}
47