“This is the 24th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

First, preparation

(1) Back-end environment construction

1. Create a Vue+node folder, create a subfolder serve, open CMD init -y in the folder to initialize the project description file

Json stores project dependency information

② Package-lock. json stores dependent version information

2. Install project dependencies

1) name: express

Installation: NPM I Express-S

Purpose: Backend framework

(2) the name: nodemon

Installation: NPM install -g nodemon

Function: Automatically restarts the service when the code changes

(3) name: mongoose

Installation: NPM I MongooSE-S

Role: Database

(4) name: body – parser

Install: NPM I body-parser-s

Function: The module will handle application/ X-www-form-urlencoded, Application/JSON request bodies. After passing through this middleware, request parameters can be accessed in the req.body of all routing processors

(5) name: cors

Install: NPM I CORON-s

Purpose: Resolve cross-domain problems

3. Create the app.js main entry file in the serve folder

4. Create a model folder in the serve folder to store database files

5. Create a route folder in the serve folder to store routing files

(2) Front-end environment construction

1. In the Vue+node folder, open CMD and enter Vue create View to build the front-end environment

2. CD view Go to the directory and enter NPM run serve to start the service

3. Introduce the elementUI component library vue Add Element

4. Delete what you don’t need

5. In the views folder, create register. vue, index. vue, and NotFound

6. Run NPM I axios -s to install axios

Second, back-end development

1. Configure the Express framework, create a website server, and listen to port 3000

Const express = require("express"); // Create web server const app = express(); / / listener port app. Listen (3000, () = > {the console. The log (" server startup success ")});Copy the code

2. Configure routes on the registration page. Create register.js in the Route folder and configure the registration request path in the register.js file

Const express = require("express"); Const register = express.router (); / / match secondary request path register. Post ("/", (the req, res) = > {res. Send (" hello world ")}); Module. exports = register; // Export route objects as module members.Copy the code

3. Import the routing object in app.js and configure the level-1 request path

Const register = require("./route/register"); Use ("/register", register);Copy the code

4. Run the nodemon app.js command to start the service

5. Access the browser addresshttp://localhost:3000/registerYou can see Hello World

6. Enable the interface debugging tool Postmanlocalhost:3000/registerYou can also see Hello World

7. Create connect.js under model to connect to the database

// introduce mongoose module const mongoose = require("mongoose"); / / store database address const mongoURL = "mongo: / / localhost/VueAndNode" / / avoid warning mongoose set (' useCreateIndex, true); Mongoose. Connect (mongoURL,{useNewUrlParser: true,useUnifiedTopology: True}). Then (() = > console. The log (" database connection success) "). The catch (() = > console. The log (" database connection "));Copy the code

8. Introduce connect.js to app.js for database connection

// require("./model/connect");Copy the code

9. Create user.js under the model folder to create a user collection

Const mongoose = require("mongoose"); const { Schema, model } = mongoose; // Set the set rule const userSchema = new Schema({account: {type: String, required: true, unique: }, password: {type: String, required: true}}); Const User = model("User", userSchema); Module.exports = {User: User,}Copy the code

Use the mongodb Compass tool to check whether the collection is set up successfully and comment out the code that inserted the test data

Create ({account:"17615180174", password:"12346",}); // Insert a test data. user.create ({account:"17615180174", password:"12346",});Copy the code

The test data has been inserted and the collection has been created successfully

11. Configure body-paser in app.js

Const bodyParser = require("body-parser"); const bodyParser = require("body-parser"); // Handle post request parameters app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json({ extended: false }));Copy the code

\

Implement the register interface in register.js under route

Const {User} = require(".. /model/user.js"); Register. Post ("/register", async (req, Res) => {const user = await user. findOne({account: Req.body.account}) if (user) {return res.status(409).send(" username is registered "); } else {// Add this data to the database if the User does not exist const newUser = await user.create (req.body); Return res.send(newUser); }});Copy the code

Test results in Postman show that the inserted data can be successfully returned

13. Configure CORS in app.js to solve cross-domain problems

Const cors = require('cors') // configure cors app.use(cors())Copy the code