初始化项目 npm init -y
安装express npm install express –save
新建index.js,index.html.
index.html.
<!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>
<div style="margin: 10px;"><input type="button" id="ubtn" value="确定"></div>
<div id="see" style="margin: 10px;"></div>
</body>
<script>
let btn = document.getElementById("ubtn");
let see = document.getElementById("see");
btn.onclick = function () {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) { //响应完成且成功
see.innerHTML = xhr.responseText
} else { //响应完成但不成功
alert('响应完成但失败!' + xhr.status);
see.innerHTML = "";
}
}
}
myurl = 'http://localhost:8000/123'
xhr.open('GET', myurl, true);
xhr.send();
}
</script>
</html>
index.js
const express = require('express');
const app = express();
const cors = require('cors');//跨域
app.use(cors());
app.listen(8000, () => {
console.log('服务启动');
})
app.get('/123', (req, res) => {
res.send("test")
})
运行node index.js