請參考以下代碼使用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/
你做一個 「故宮安裝」? – Roy 2014-09-25 19:02:51
有兩點:第一,在這個例子中,使用的端口是'80',而不是'8080'。其次,你應該嘗試'http:// localhost:8080/api/players',或'http:// localhost:80/api/players'(我不知道你使用的是什麼數字)。 – 2014-09-25 19:03:27
@Roy是的,我做了一個「npm安裝」。 – dukable 2014-09-25 19:04:03