const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
let url = req.url;
console.log(url);
switch (req.method){
case 'GET':
if(url === '/'){
let html = fs.readFileSync('./template.html', 'utf8');
res.writeHead(200, {'Content-type': 'text/html'});
res.end(html);
}
else if(url === '/test'){
}
break;
case 'POST':
let chunks = Buffer.alloc(0);
let chunksLength = 0;
req.on('data', chunk => {
chunks = Buffer.concat([chunks, chunk], chunksLength + chunk.length);
chunksLength = chunks.length;
});
req.on('end', () => {
});
break;
default: break;
}
}).listen(80, `127.0.0.1`, () => {console.log(`Server running at http://127.0.0.1`);});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>template</title>
<link rel="icon" href="https://dss1.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/weather/icons/a7.png" type="image/x-icon">
</head>
<body>
<button id="bt">赵客缦胡缨,吴钩霜雪明。</button>
<script>
const origin = `http://127.0.0.1`
let bt = document.querySelector('#bt');
bt.onclick = e => {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4){
console.log(xhr.response);
}
};
xhr.open('GET', `${origin}/test`);
xhr.send(null);
};
</script>
</body>
</html>
标签:http,NodeJS,url,req,最小,xhr,let,chunks,服务器 From: https://blog.51cto.com/u_13128132/6096464