实例下载:百度云盘免密码
(): 指注释
一、准备工作
1.安装express
npm install express -g
npm install express-generator -g
2.初始化项目
express APIServer(项目名称)
cd APIServer && npm install
二、启动服务器
npm start
启动完成后终端将输出 node ./bin/www
在浏览器中访问 http://localhost:3000/
三、基本使用
定义一个路由的基本格式为:
app.METHOD(PATH, HANDLER)
想要实现一个获取用户信息接口该怎么写呢?(获取url参数 依赖于url模块)
/routers/user.js
function User() {
this.name;
this.city;
this.age;
}
module.exports = User;
/routers/users.js
var User = require('./user');
var URL = require('url');
router.get('/getUserInfo', function(req, res, next) {
var user = new User();
var params = URL.parse(req.url, true).query;
if(params.id == '1') {
user.name = "ligh";
user.age = "1";
user.city = "北京市";
}else{
user.name = "SPTING";
user.age = "1";
user.city = "杭州市";
}
var response = {status:1,data:user};
res.send(JSON.stringify(response));
});
调用方式(可在浏览器打开)
http://localhost:3000/users/getUserInfo?id=1
http://localhost:3000/users/getUserInfo?id=2
四、Post请求额外处理
1.引用body-parser中间件
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
2.允许跨域
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
实例:修改/app.js 和 /routes/all.js两个文件
/app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = require('./routes/all');
/*
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use('/', index);
app.use('/users', users);
var login = require('./routes/login');
app.use('/login', login);
*/
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
/routes/all.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
var app = express();
var URL = require('url');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/login', function(req, res, next) {
var params = req.body;
var user = {}
user.u = params.username
var response = {status:1,data:user};
res.send(JSON.stringify(response));
});
router.get('/login', function(req, res, next) {
var params = URL.parse(req.url, true).query;
console.log(params)
var user = {}
user.u = params.username
var response = {status:2,data:user};
res.send(JSON.stringify(response));
});
router.get('/users', function(req, res, next) {
res.send('respond with a resource');
});
app.use('/', router)
module.exports = app;
/package.json
{
"name": "apiserver",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.15.5",
"jade": "~1.11.0",
"morgan": "~1.9.0",
"serve-favicon": "~2.4.5"
},
"devDependencies": {
"body-parser": "^1.18.2",
"url": "^0.11.0"
}
}