1- const express = require ( ' express' ) ;
2- const cors = require ( ' cors' ) ;
1+ const express = require ( " express" ) ;
2+ const cors = require ( " cors" ) ;
33const app = express ( ) ;
4+ var bodyParser = require ( "body-parser" ) ;
5+
6+ app . use ( bodyParser . urlencoded ( { extended : false } ) ) ;
7+
8+ app . use ( bodyParser . json ( ) ) ;
9+
410app . use ( cors ( ) ) ;
511
6- const { connect} = require ( ' ./mongo' ) ;
12+ const { connect } = require ( " ./mongo" ) ;
713
8- const url = ' mongodb://localhost:27017' ;
14+ const url = " mongodb://localhost:27017" ;
915
10- const dbName = ' phucam' ;
11- const collectionName = ' gospel' ;
16+ const dbName = " phucam" ;
17+ const collectionName = " gospel" ;
1218
1319const main = ( ) => {
1420 // Make database connection to MongoDB server.
1521 connect (
1622 url ,
17- dbName ,
23+ dbName
1824 )
1925 // When the connection to the MongoDB has been successfull.
2026 . then ( db => {
2127 // Get the reference to the collection.
2228 const gospelCollection = db . collection ( collectionName ) ;
2329
2430 // Render default page.
25- app . get ( '/' , function ( req , res ) {
26- res . send ( ' Hello World' ) ;
31+ app . get ( "/" , function ( req , res ) {
32+ res . send ( " Hello World" ) ;
2733 } ) ;
2834
2935 // HTTP GET at /gospel with all of the documents from `gospel` collection.
30- app . get ( ' /gospel' , ( req , res ) => {
36+ app . get ( " /gospel" , ( req , res ) => {
3137 gospelCollection . find ( { } ) . toArray ( ( err , docs ) => {
3238 if ( err ) {
3339 console . error ( err ) ;
@@ -38,12 +44,25 @@ const main = () => {
3844 res . json ( docs ) ;
3945 } ) ;
4046 } ) ;
47+
48+ // HTTP POST: Insert a document.
49+ app . post ( "/gospel" , ( req , res ) => {
50+ const color = req . body . color ;
51+ const content = req . body . content ;
52+ gospelCollection . insertOne (
53+ { color : color , content : content } ,
54+ ( err , result ) => {
55+ if ( err ) throw err ;
56+ res . send ( "Success" ) ;
57+ }
58+ ) ;
59+ } ) ;
4160 } )
4261 . catch ( err => {
43- console . error ( ' Khong the connect database' ) ;
62+ console . error ( " Khong the connect database" ) ;
4463 } ) ;
4564 app . listen ( 4000 , ( ) => {
46- console . log ( ' Server is up on port 4000' ) ;
65+ console . log ( " Server is up on port 4000" ) ;
4766 } ) ;
4867} ;
4968
0 commit comments