简体   繁体   中英

Basic REST API with Nodejs and Express4

I have been trying to create a quick REST API using Nodejs and Express4 as I need an API quickly to make a prototype. While I need all basic CRUD operations, I tried to run the example from the following URL: http://runnable.com/U7bnCsACcG8MGzEc/restful-api-with-node-js-express-4 The example at this address only supports GET, but I believe I could quickly adapt it to support POST, PUT and DELETE. I do not care of having the data on memory, it is even preferable.

You can click to see the code there.

However, once I have started my server and go on http://localhost:8080/players

I get "Cannot GET /players" in my browser.

Any idea? If somebody has another short/quick example of a REST API with Nodejs with in-memory persistence, I'll take it as well :)

If you want to create quick API with CRUD operation then try npm deployd , but there is not express. If u love to code then use express-generator

Please refer following code to create REST API using ExpressJS.

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;

Link : http://codeforgeek.com/2015/03/restful-api-node-and-express-4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM