对于刚开始不会node写接口和调用接口,可以通过这个清晰的初步了解到整个过程。
1.在node官网https://nodejs.org/en/下载node.js
2.在自己电脑中新建一个文件夹,例如:D:/node
3.在该新建的文件夹中,打开命令行窗口(shift+右击)
4.通过npm init创建package.json文件
通过 npm install express 安装express模块,后面要用到的
5.在node文件夹中新建app.js文件,将下面的代码复制到app.js文件中
var express=require('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);
})
6.在命令行中,运行$ node app.js
![c8c8760c44be941701338796b0cc3ac9.png](https://i-blog.csdnimg.cn/blog_migrate/43522a6760d0868da2b1bb4389fea226.jpeg)
7.在浏览器地址栏输入localhost:3000/123
![79adf1d61f47b37a3bacbbc23bc5dc42.png](https://i-blog.csdnimg.cn/blog_migrate/b67a4e213564fae1aee7fdcbaa557c8d.jpeg)
8.调用接口
新建文件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>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$.ajax({
type:'get',
url:'http://localhost:3000/123',
success:function(data){
console.log(data);
},
error:function(){
console.log('error');
}
})
</script>
</body>
</html>
9.在浏览器中打开index.html
![e598492d0e27282599b73ce4f5327c60.png](https://i-blog.csdnimg.cn/blog_migrate/d7f00e672a6d6e8c183987f2056e6d94.jpeg)
注:每次修改了app.js,调用接口需要重新运行一下$ node app.js