// app.js const http = require('http'); const fs = require('fs'); let server = http.createServer(); server.on('request', (req, res)=>{ if(req.url === '/'){ fs.readFile('./index.html', (err, data)=>{ res.writeHead(200,{'content-type':'text/html;charset=utf-8'}); res.end(data); }) }else if(req.url === '/test' && req.method ==='GET'){ res.writeHead(200,{'content-type':'application/octet-stream'}); setInterval(function() { res.write(''+ Date.now()+ '^_^'); },1000); } req.on('data', (data)=>{ console.log(data.toString()); }) }); server.listen(9999, ()=>{ console.log('服务器9999 已开启'); })
<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <span id='info'></span> <button id='btn'>点我发</button> </body> <script> var info = document.querySelector('#info'); document.querySelector('#btn').onclick = function(){ var xhr = new XMLHttpRequest(); xhr.open('get', '/test'); xhr.send(); xhr.onreadystatechange = function(){ console.log(xhr.readyState); //1,2,3,4 console.log(xhr.responseText); var arr = xhr.responseText.split('^_^') console.log(arr[arr.length-2]); info.innerText = arr[arr.length-2]; } } </script> </html>