File tree 5 files changed +90
-0
lines changed
5 files changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ node_modules
Original file line number Diff line number Diff line change
1
+ ## Simple RESTFul API with Node.js and Express
2
+
3
+
4
+ Article : [ มาทำ RESTFul API ด้วย Node.js กับ Express กันดีกว่า] ( http://devahoy.com/2014/09/restful-api-with-node-js-and-express )
Original file line number Diff line number Diff line change
1
+ var users = require ( './users' ) ;
2
+ var app = require ( 'express' ) ( ) ;
3
+ var bodyParser = require ( 'body-parser' ) ;
4
+
5
+ var port = process . env . PORT || 7777 ;
6
+
7
+ // parse application/json
8
+ app . use ( bodyParser . json ( ) ) ;
9
+ app . use ( bodyParser . urlencoded ( {
10
+ extended : true
11
+ } ) ) ;
12
+
13
+ app . get ( '/' , function ( req , res ) {
14
+ res . send ( '<h1>Hello Node.js</h1>' ) ;
15
+ } ) ;
16
+
17
+ app . get ( '/user' , function ( req , res ) {
18
+ res . json ( users . findAll ( ) ) ;
19
+ } ) ;
20
+
21
+ app . get ( '/user/:id' , function ( req , res ) {
22
+ var id = req . params . id ;
23
+ res . json ( users . findById ( id ) ) ;
24
+ } ) ;
25
+
26
+ app . post ( '/newuser' , function ( req , res ) {
27
+ var json = req . body ;
28
+ res . send ( 'Add new ' + json . name + ' Completed!' ) ;
29
+ } ) ;
30
+
31
+ app . listen ( port , function ( ) {
32
+ console . log ( 'Starting node.js on port ' + port ) ;
33
+ } ) ;
Original file line number Diff line number Diff line change
1
+ {
2
+ "name" : " devahoy-nodejs" ,
3
+ "version" : " 0.0.1" ,
4
+ "description" : " Devahoy Node.js with Express 4 Tutorial" ,
5
+ "main" : " index.js" ,
6
+ "dependencies" : {
7
+ "body-parser" : " ^1.8.3" ,
8
+ "express" : " ^4.9.4"
9
+ }
10
+ }
Original file line number Diff line number Diff line change
1
+ var users = [
2
+ {
3
+ "id" : 1 ,
4
+ "username" : "goldroger" ,
5
+ "name" : "Gol D. Roger" ,
6
+ "position" : "Pirate King"
7
+ } ,
8
+ {
9
+ "id" : 2 ,
10
+ "username" : "mrzero" ,
11
+ "name" : "Sir Crocodile" ,
12
+ "position" : "Former-Shichibukai"
13
+ } ,
14
+ {
15
+ "id" : 3 ,
16
+ "username" : "luffy" ,
17
+ "name" : "Monkey D. Luffy" ,
18
+ "position" : "Captain"
19
+ } ,
20
+ {
21
+ "id" : 4 ,
22
+ "username" : "kuzan" ,
23
+ "name" : "Aokiji" ,
24
+ "position" : "Former Marine Admiral"
25
+ } ,
26
+ {
27
+ "id" : 5 ,
28
+ "username" : "shanks" ,
29
+ "name" : "'Red-Haired' Shanks" ,
30
+ "position" : "The 4 Emperors"
31
+ }
32
+ ] ;
33
+
34
+ exports . findAll = function ( ) {
35
+ return users ;
36
+ } ;
37
+
38
+ exports . findById = function ( id ) {
39
+ for ( var i = 0 ; i < users . length ; i ++ ) {
40
+ if ( users [ i ] . id == id ) return users [ i ] ;
41
+ }
42
+ } ;
You can’t perform that action at this time.
0 commit comments