<!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head>
<body> <h1>你好</h1> <button>点我获取用户数据</button> </body> <script> const btn = document.querySelector('button'); btn.onclick = function () { const xhr = new XMLHttpRequest(); //同源可以省略,只写/data xhr.open('GET', '/data'); xhr.send(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status <= 200 && xhr.status < 300) { console.log(xhr.response); } } } }
</script>
</html> ==================server.js====================
const { request, response } = require('express'); const express = require('express'); const app = express(); app.get('/home', (request, response) => { response.sendFile(__dirname + '/index.html'); }) app.get('/data', (request, response) => {
const data = { name: 'xiaoming', age: '18' }; //setTimeout(() => { response.send(JSON.stringify(data)); //}, 3000);
})
app.listen(8000, () => { console.log('服务已经启动,8000端口监听中.......'); })