This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

Build API server using Node + Express + mongodb

Create a project

mkdir <project-name>
Copy the code

Initialize the project

npm init -y # NPM package.json initialization
yarn add express # express installation
Copy the code

Create entry files and initialize configurations

mkdir server.js
Copy the code

Introduce Express and Initial Configuration of Express

// server.js
const express = require("express"); / / into the express
const app = express(); // Express initialization

app.get("/".(req, res) = >{ // Create a routing interface
    res.send("Hello Express")})const port = process.env.PORT || 5000; // Set the port number

app.listen(port, () = >{ // Start the service and listen on the port
    console.log("Server is Running on http://localhost:${port}")})Copy the code

Configure package.json to start the script command

// package.json

"scripts": {  "start": "node server.js"},
"server""nodemon server.js" // Install Nodemon to start hot deployment
Copy the code

Connect to Mongodb using Mongoose

yarn add mongoose
Copy the code
//@Server.js
const express = require("express");

const mongoose = require("mongoose");
mongoose.set('useFindAndModify'.false);

const app = express();

// DB Config Connects to the database
const db = require("./config/keys").mongoURI;// Create the config directory to store static constants
mongoose.connect(db, {
  user: <usernmae>,
  pass: <password>,
  useNewUrlParser: true.useUnifiedTopologytrue
}).then(res= >{
  console.log(`MongoDB connected! `)
}).catch(err= >{
  console.log(`MongoDB connected Failed: \n ${err}`)})Copy the code

Creating a Configuration File

touch config/keys.js
Copy the code
// @config/keys.js
module.exports = {
    mongoURI: "Mongo: / / 127.0.0.1:27017 / < dbname >"};Copy the code

Create a model Schema

Create a directory models to store the models

Create a User model user.js file

// User.js
const mongoose = require('mongoose');
const Schema =  mongoose.Schema;

const UserSchema = new Schema({    
    username: {type: String.require: true   
    },  
    password: {      
        type: String.require: true   
    }, 
    data: {        
        type: Date.default: Date.now()   
    }
});
module.exports = User = mongoose.model('user', UserSchema);
Copy the code

Create the Route Api

Create a directory routes/ API

Create the user routing file user.js

// @routes/api/users.js
const express = require('express'); / / into the express
const router = express.Router();// Use the Express Router
const User = require(".. /.. /models/User"); // Introduce the User model

// Add a user
router.get("/add".(req, res) = > {   
    const newUser = new User({    
        username: "test".password: "test"   
    })    
    newUser.save().then(user= > {      
        res.json({          
        msg: "New user success".data: user      
        })   
    }).catch(err= >{      
        console.log(err); })});module.exports = router; // Export the routing module
Copy the code

In server.js

//@server.js
const users = require('./routes/api/users'); // Import the Users route
/ /...
app.use('/api/users', users); // Configure the Users route and use it
Copy the code

Express accesses static resources

Create a static resource directory that can be used as an example

// @server.js
const path = require('path'); / / import path

app.use(express.static(path.join(__dirname, 'public'))); // Specify a static resource directory

// localhost: port number/file name for direct access
Copy the code

The Route API returns static pages

const fs = require("fs");

app.get("/".(req,res) = >{   
    res.writeHead(200, {'Content-Type':'text/html'}); 
        fs.readFile('./public/index.html'.'utf-8'.function(err,data){      
            if(err){           
                throw err ;  
             }       
             res.end(data);  
        });
});
Copy the code