data.json文件:
{
"students": [
{
"id": "1",
"name": "张小三",
"age": 18
}, {
"id": 2,
"name": "张三",
"age": 18
}, {
"id": 3,
"name": "张小",
"age": 18
}, {
"id": 4,
"name": "张三",
"age": 18
}, {
"id": 5,
"name": "张三",
"age": 18
}, {
"id": 6,
"name": "张三",
"age": 18
}
]
}
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(8020,function(){
console.log(1);
});
getdata.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script>
var xml = new XMLHttpRequest();
xml.onreadystatechange=function(){
if(xml.readyState==4&&xml.status==200){
console.log(xml.responseText)
}
}
xml.open('get','http://localhost:8020/');
xml.send();
</script>
</html>
结果图: