目录如下
server.js
yarn add -D express nodemon -D
var express = require("express")
var app = new express()
// 后端解决跨域问题
app.all("*",(req,res,next)=>{
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-headers","X-Requested-with");
res.header("Access-Control-Allow-Headers","Content-Type");
res.header("Access-Control-Allow-Methods","PUT,POST, GET,DELETE,OPTIONS")
next()
})
app.get("/",(req,res,next)=>{
let arr = [
{
id:1,
name: '张三1'
},
{
id:2,
name: '张三2'
},
{
id:3,
name: '张三3'
},
]
res.send(arr)
})
var port = 9527
app.listen(port,()=>{
console.log(`服务器启动... 端口是 http://localhost:${port}`)
})
启动 npx nodemon server.js
<body>
<button onClick="clickHandler()">请求数据</button>
<script>
var fetchReq = () =>{
fetch("http://localhost:9527",{
method: "GET",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(res=>{
// return res.text()
return res.json()
}).then(resp=>{
console.log("resp",resp)
})
}
var clickHandler = ()=>{
fetchReq()
}
</script>
</body>
展示页面