第一步:安装express
yarn add express
第二步:编写源数据
根据你想要返回的格式编写数据,新建文件data.json
{
"students": [
{
"id": "1",
"name": "张一",
"age": 80
}, {
"id": 2,
"name": "张二",
"age": 73
}, {
"id": 3,
"name": "张三",
"age": 66
}, {
"id": 4,
"name": "张四",
"age": 41
}, {
"id": 5,
"name": "张五",
"age": 19
}, {
"id": 6,
"name": "张六",
"age": 8
}
]
}
第三步:配置请求
新建文件 get.js
var express = require('express');
var fs = require('fs')
var app=express();
app.all('*', function(req, res, next) { //设置跨域访问
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.get('/',function(req,res){
fs.readFile('./data.json',function(err,data){
if(err){
console.log(0);
}else{
res.send(JSON.parse(data))
}
})
})
app.listen(8888,function(){ // 监听一个不常用的端口
console.log("服务启动的会log这个提示");
});
第四步:在页面中发起网络请求
<div>使用Ajax</div>
<button onclick="useAjax()">
点我获取数据
</button>
<script>
function useAjax() {
let xmlhttp;
if (window.XMLHttpRequest) {
// 如果浏览器支持ajax,则创建一个ajax对象
xmlhttp = new XMLHttpRequest();
// 在某个事件时执行函数
xmlhttp.onreadystatechange = function () {
// 如果当前返回是OK的
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementsByTagName('div')[0].innerHTML = xmlhttp.responseText;
}
}
// 发送请求,首先open(method,url,async)
xmlhttp.open("GET", "http://localhost:8888/", true);
// 定义过请求事宜后,发送!
xmlhttp.send();
}
}
</script>
第五步:启服务
在终端进入对应目录文件下输入指令
node get.js
第六步:打开对应端口
eg:根据我的配置,需要打开http://localhost:8888/,页面上会有源数据显示
第七步:在页面中发送网络请求
就可以请求到相应的数据进行格式处理和符合业务的操作啦~