Open uniquejava opened 8 years ago
mkdir node-api && cd node-api
npm init
npm install --save express mongoose body-parser
node server.js
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/node-api');
var Bear = require('./app/models/bear');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.use(function (req, res, next) {
console.log('something is happending');
next();
});
router.get('/', function (req, res) {
res.json({message: 'horray! welcome to our api!'});
});
router.route('/bears')
.post(function (req, res) {
var bear = new Bear();
bear.name = req.body.name;
bear.save(function (err) {
if (err) {
res.send(err);
}
res.json({message: 'Bear created!'});
});
}).get(function (req, res) {
Bear.find(function (err, bears) {
if (err) {
res.send(err);
}
res.json(bears);
});
});
router.route('/bears/:bear_id')
.get(function (req, res) {
Bear.findById(req.params.bear_id, function (err, bear) {
if (err) {
res.send(err);
}
res.json(bear);
});
})
.put(function (req, res) {
Bear.findById(req.params.bear_id, function (err, bear) {
if (err) {
res.send(err);
}
bear.name = req.body.name;
bear.save(function (err) {
if (err) {
res.send(err);
}
res.json({message: 'Bear updated!'});
});
});
})
.delete(function (req, res) {
Bear.remove({_id: req.params.bear_id}, function (err, bear) {
if (err) {
res.send(err);
}
res.json({message: 'successfully deleted.'});
});
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port' + port);
bear.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
http://expressjs.com/en/guide/error-handling.html
Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen()
.
If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).
var express = require('express');
var app = express();
app.listen(3000);
The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
The app.listen() method returns an http.Server
object and (for HTTP) is a convenience method for the following:
app.listen = function() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
router.use(require('./app/utils/cors'));
cors.js
module.exports = function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length,Authorization,Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' CyperCore');
if (req.method == "OPTIONS") res.send(200);
else next();
};
https://github.com/expressjs/generator
$ npm install -g express-generator
$ express -e hello && cd hello
Options
-h, --help output usage information
--version output the version number
-e, --ejs add ejs engine support
--hbs add handlebars engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
参考: http://expressjs.com/en/starter/generator.html
npm install express-generator -g
npm install nodemon -g
express -e --git getting-mean
cd getting-mean && npm install
然后在webstorm配置configurations:
node interpreter选择~/.nvm/versions/node/v4.6.2/bin/nodemon
js选择bin/www
然后点击run button就可以愉快的玩耍了.
Express源码学习笔记:
http://www.cnblogs.com/lovesueee/tag/express/
[译]RESTful API 设计最佳实践 https://segmentfault.com/a/1190000011516151
RESTful API设置指南: http://www.ruanyifeng.com/blog/2014/05/restful_api.html
阅读: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
练习写的代码: https://github.com/uniquejava/node-api
app 目录是放后端js文件的,, public目录是放前端的..