Basic REST API with Nodejs and Express4
Basic REST API with Nodejs and Express4
我一直在尝试使用Nodejs和Express4创建一个快速的REST API,因为我需要一个API来快速制作原型。虽然我需要所有基本的CRUD操作,但我尝试从以下URL运行该示例:http://runnable.com/U7bnCsACcG8MGzEc/restful-api-with-node-js-express-4这个地址的示例只支持GET,但我相信我可以快速调整它以支持POST、PUT和DELETE。我不在乎内存中有数据,这甚至更可取。
您可以单击此处查看代码。
然而,一旦我启动服务器并使用http://localhost:8080/players
我在浏览器中看到"无法获取/播放器"。
知道吗?如果有人有另一个带有Nodejs的带有内存持久性的REST API的简短/快速示例,我也会这样做:)
如果您想使用CRUD操作创建快速API,请尝试npm deployd,但没有express。如果你喜欢编码,那么使用快速生成器
请参考以下代码使用ExpressJS创建REST API。
Server.js
var express = require("express");
var mysql = require("mysql");
var bodyParser = require("body-parser");
var rest = require("./REST.js");
var app = express();
function REST(){
var self = this;
self.connect_to_mysql();
}
REST.prototype.connect_to_mysql = function() {
var self = this;
var pool = mysql.createPool({
connectionLimit : 100,
host : 'localhost',
user : 'root',
password : '',
database : 'restful_api_demo',
debug : false
});
pool.getConnection(function(err,connection){
if(err) {
self.stop(err);
} else {
self.configureExpress(connection);
}
});
}
REST.prototype.configureExpress = function(connection) {
var self = this;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
app.use('/api', router);
var rest_router = new rest(router,connection);
self.start_server();
}
REST.prototype.start_server = function() {
app.listen(3000,function(){
console.log("All right ! I am alive at Port 3000.");
});
}
REST.prototype.stop = function(err) {
console.log("ISSUE WITH MYSQL 'n" + err);
process.exit(1);
}
new REST(); // Instantiate class.
REST.js
function REST_ROUTER(router,connection) {
var self = this;
self.handle_routes(router,connection);
}
REST_ROUTER.prototype.handle_routes = function(router,connection) {
router.get("/",function(req,res){
res.json({"Message" : "Hello World !"});
})
}
module.exports = REST_ROUTER;
链接:http://codeforgeek.com/2015/03/restful-api-node-and-express-4/
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Rails 3.2 and Paloma gem
- Backbone, TypeScript, and super
- iframe and JavaScript on different pages
- JSON and jQuery Search
- Flash and External Javascript
- Basic REST API with Nodejs and Express4