- 安装node
- 创建一个文件夹(例如node)
- 初始化 npm init
- 在文件夹中调出命令窗口,npm install express –save 安装express模块(有点慢得等等)
-
在node文件夹中建立新文件 app.js
文件目录 image.png
var express=require('./node_modules/express');
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();
});
var questions=[
{
data:213,
num:444,
age:12
},
{
data:456,
num:678,
age:13
}];
//写个接口123
app.get('/123',function(req,res){
res.status(200),
res.json(questions)
});
//配置服务端口
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
})
-
启动 node app.js
image.png - image.png
-
建立 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="node">
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
var nodeData;
$.ajax({
type: 'get',
url: 'http://localhost:3000/123',
success: function (data) {
console.log(data);
nodeData = data;
for(var i=0;i<data.length;i++){
$("#node").append(`<div>data:${data[i].data}</div><div>num:${data[i].num}</div><div>age:${data[i].age}</div><br>`)
}
},
error: function () {
console.log('error');
}
})
</script>
</html>
数据结果
image.png
网友评论