首先默认装好了node环境
1、
npm init
创建package.json文件;
2、创建一个app.js文件,当然别的名字也可以,这个文件是你整个程序的入口。
//引入express 创建服务器
var express = require('express');
var app = express();
// 需要对表单数据进行解析的,安装bodyParser
var bodyParser = require('body-parser'); //解析函数
app.use(bodyParser.json()); //json请求
app.use(bodyParser.urlencoded({ extended:true})); //表单请求
// 设置跨域访问
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 info = [
{
data:123,
num:1,
age:11
},{
data:456,
num:2,
age:22
}
];
// 配置接口api
app.get('/api11',function (req,res) {
res.status(200),
res.json(info)
// res.send(info)
})
app.post('/api12',function (req,res) {
console.log(req.stack);
console.log(req.body);
console.log(req.url);
console.log(req.query);
// res.json(req.body)
res.json(info)
})
// 配置服务端口
var server = app.listen(3001,function(){
// var host = server.address().address;
// var port = server.address().port;
// console.log('listen at http://%s%s',host,port);
console.log('服务启动');
})
补充:
res.json
这个方法是以json对象的形式返回去;
res.send
以页面的方式返回去
res.download
以文件的方式返回去,前端请求会下载此文件
3、安装express框架
npm install express --save
4、安装node.js body 解析中间件
npm install body-parser --save
涉及到post请求时需要此插件,而且post请求不能直接在浏览器打开,可以在postman中调试查看
5、新建一个html文件,如index.html,里面用ajax请求一下
<!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>
$(function(){
console.log(11111111111);
// get请求
$.ajax({
type:'get',
url:'http://localhost:3001/api11',
success:function(data){
console.log(data);
},
error:function(err){
console.log(err);
}
})
// post请求
$.ajax({
type:'post',
url:'http://localhost:3001/api12',
data:{name:'gxy',pass:'111111'},
success:function(data){
console.log(data);
},
error:function(err){
console.log(err);
}
})
})
</script>
</body>
</html>
6、终端输入
node app.js
启动服务
版权声明:本文为weixin_45024541原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。