1024programmer Java Example of webpack4+express+mongodb+vue implementing addition, deletion, modification and query

Example of webpack4+express+mongodb+vue implementing addition, deletion, modification and query

Before explaining, let’s take a look at the effect as follows:

1) The effect of the entire page is as follows:

2) The effect of adding new data is as follows:

3) The new addition is successful as follows:

4) The effect of editing data is as follows:

5) The result of successful editing is as follows:

6) The effect of deleting data is as follows:

7) The effect of successful deletion is as follows:

8) The query results are as follows:

With the above effect, we will still do the same as before. Let’s first look at the structure of our entire project as follows:

 ### The directory structure is as follows:
 demo1 # project name
 | |--- dist # Directory file generated after packaging
 | |--- node_modules # All dependent packages
 | |----database # Database related file directory
 | | |---db.js # Database connection operation of mongoose class library
 | | |---user.js # Schema Create model
 | | |---addAndDelete.js # Add, delete, modify and check operations
 | |--- app
 | | |---index
 | | | |-- views # Store all vue page files
 | | | | |-- list.vue # List data
 | | | | |-- index.vue
 | | | |-- components # Store components common to vue
 | | | |-- js # Store js files
 | | | |-- css # Store css files
 | | | |-- store # store warehouse
 | | | | |--- actions.js
 | | | | |--- mutations.js
 | | | | |--- state.js
 | | | | |--- mutations-types.js
 | | | | |--- index.js
 | | | | |
 | | | |-- app.js # vue entry configuration file
 | | | |-- router.js # Routing configuration file
 | |--- views
 | | |-- index.html # html file
 | |--- webpack.config.js # webpack configuration file
 | |--- .gitignore
 | |--- README.md
 | |--- package.json
 | |--- .babelrc # babel transcoded file
 |--- app.js # express entry file

The directory structure above is the architecture diagram of my entire project. The database directory stores db.js. This file mainly uses the mongoose database connection operation. The user.js file creates a Schema model, which can also be understood as a table. Structure, the addAndDelete.js file implements addition, deletion, modification and query operations.

First build the database locally, and then learn slowly. My article here to implement vue+mongodb to implement addition, deletion, modification and query is also based on the above articles, especially this article using the Mongoose class The library implements simple addition, deletion, modification and query

(https://www.ddpool.cn/article/150381.htm). The operations of adding, deleting, modifying and using Schema to create models are all based on this article and then reconstructed using vue. Down. This article is also developed based on the Ele.me vue component.

Let’s first talk about the code structure:

1) Create a server using express

First, we create a new app.js in the root directory of the project. The main function of this app.js is to start the server on port 3001 and use bodyParser to parse the data, as shown in the following code:

 //Introduce express module
 const express = require('express');

 //Create app object
 const app = express();

 const addAndDelete = require('./database/addAndDelete');

 const bodyParser = require("body-parser")

 app.use(bodyParser.json());

 app.use(bodyParser.urlencoded({ extended: false }));

 // use
 app.use('/api', addAndDelete);

 //Define the server startup port
 app.listen(3001, () => {
  console.log('app listening on port 3001');
 });

After entering the root directory of our project, run node app.js to create a server page at http://127.0.0.1:3001.

2) Database connection

Link to the mongodb://localhost:27017/dataDb database in database/db.js. Use the mongoose class library. If you don’t understand the mongoose class library, you can return to my article (https://www.ddpool.cn/article/150381.htm) with the following code:

 var mOngoose= require('mongoose');
 var DB_URL = 'mongodb://localhost:27017/dataDb';

 /* Link */
 mongoose.connect(DB_URL);

 /* Link successful */
 mongoose.connection.on('connected', function() {
  console.log('Mongoose connection open to ' + DB_URL);
 });

 //Link exception
 mongoose.connection.on('error', function(err) {
  console.log('Mongoose connection error:' + err);
 });

 // link broken

 mongoose.connection.on('disconnected', function() {
  console.log('Mongoose connection disconnected');
 });
 module.exports = mongoose;

3) Create data model

Use Schema to create a model in database/user.js. That is to say, the dataDb above is the name of the database. The model created using schema here is the fields of the table structure. It has the following three fields: name, age, and sex. The code is as follows:

 /*
  Define a user's Schema
 */
 const mOngoose= require('./db.js');
 const Schema = mongoose.Schema;

 //Create a model
 const UserSchema = new Schema({
  name: { type: String }, // Attribute name, type is String
  age: { type: Number, default: 30 }, // Attribute age, type is Number, default value is 30
  sex: { type: String }
 });

 // Export model module
 const User = module.exports = mongoose.model('User', UserSchema);

4) Implement the add, delete, modify and query routing interface

The code for all additions, deletions, modifications and queries below is as follows (if you don’t understand the code, just go back and read this article: https://www.ddpool.cn/article/150381.htm):

 //Introduce express module
 const express = require('express');

 const router = express.Router();

 //Introduce user.js
 const User = require('./user');

 //Add a new piece of data. The interface is add.
 router.post('/add', (req, res) => {
  const user = new User({
  name: req.body.name,
  age: req.body.age,
  sex: req.body.sex
  });
  user.save((err, docs) => {
  if (err) {
   res.send({ 'code': 1, 'errorMsg': 'Add failed' });
  } else {
   res.send({ "code": 0, 'message': 'Add successfully' });
  }
  });
 });

 // Query data 
 router.post('/query', (req, res) => {
  const name = req.body.name,
  age = req.body.age,
  sex = req.body.sex;
  const obj = {};
  if (name !== '') {
  obj['name'] = name;
  }
  if (age !== '') {
  obj['age'] = age;
  }
  if (sex !== '') {
  obj['sex'] = sex;
  }
  User.find(obj, (err, docs) => {
  if (err) {
   res.send({ 'code': 1, 'errorMsg': 'Query failed' });
  } else {
   res.send(docs);
  }
  });
 });

 //Delete data based on _id
 router.post('/del', (req, res) => {
  const id = req.body.id;
  //Delete based on automatically assigned _id
  const whereid = { '_id': id };
  User.remove(whereid, (err, docs) => {
  if (err) {
   res.send({ 'code': 1, 'errorMsg': 'Deletion failed' });
  } else {
   res.send(docs);
  }
  })
 });

 // update data
 router.post('/update', (req, res) => {
  console.log(req.body)
  //Data that needs to be updated
  const id = req.body.id,
  name = req.body.name,
  age = req.body.age,
  sex = req.body.sex;
  const updateStr = {
  name: name,
  age: age,
  sex: sex
  };
  const ids = {
  _id: id
  };
  console.log(ids);
  User.findByIdAndUpdate(ids, updateStr, (err, docs) => {
  if (err) {
   res.send({ 'code': 1, 'errorMsg': 'Update failed' });
  } else {
   res.send(docs);
  }
  });
 });
 module.exports = router;

5) When building a vue page, how to request it through the interface of the page?

The basic code in app/index/views/list.vue is as follows (all html codes are based on Ele.me vue components, the most important ones are the usage of form components and form plug-ins and pop-up window plug-ins), the code As follows:

 
 
 
   
  
    
    
    
  
  
    
    
    
  
  
    
    
     
     
    
    
  
   Query
   New
   
 
 
   
   
   
   
   
   
   
   
    
    Edit
    Delete
    
   
   
 
  
   
  
    
    
    
  
  
    
    
    
  
  
    
    
     
     
    
    
  
   
   
   Cancel
   Confirm
   
  
  
   
  
    
    
    
  
  
    
    
    
  
  
    
    
     
     
    
    
  
   
   
   Cancel
   Confirm
   
  
  
   Do you confirm deletion?
   
   Cancel
   Confirm
   
  
 
 

 

6. Solve cross-domain problems and how to access the interface?

First of all, we use express to start the http://127.0.0.1:3001 server, but we use port 8081 in our webpack, which means that the page accessed is http://127.0.0.1 :8081/ If accessed in this way, there will definitely be an interface cross-domain problem, so we need to use the devServer.proxy configuration item in webpack to configure it, as follows:

 module.exports = {
  devServer: {
  port: 8081,
  // host: '0.0.0.0',
  headers: {
   'X-foo': '112233'
  },
  inline: true,
  overlay: true,
  stats: 'errors-only',
  proxy: {
   '/api': {
   target: 'http://127.0.0.1:3001',
   changeOrigin: true // Whether it is cross-domain
   }
  }
  },
 }

Because all the requests on my list.vue page are similar to this.$http.post(‘/api/query’, obj); therefore when I use /api/query to request, it will be Proxy to http://127.0.0.1:3001/api/query, so that the cross-domain problem can be solved. At the same time, we apply routing to app.js in the root directory of the project, with the following code:

 const addAndDelete = require('./database/addAndDelete');
 app.use('/api', addAndDelete);

When requesting http://127.0.0.1:3001/api/query, the /query interface method in addAndDelete.js will be automatically used.

View github code

The above is the entire content of this article. I hope it will be helpful to everyone’s study and I hope you will support me a lot.

Do you confirm deletion?

Cancel
Confirm

6. Solve cross-domain problems and how to access the interface?

First of all, we use express to start the http://127.0.0.1:3001 server, but we use port 8081 in our webpack, which means that the page accessed is http://127.0.0.1 :8081/ If accessed in this way, there will definitely be an interface cross-domain problem, so we need to use the devServer.proxy configuration item in webpack to configure it, as follows:

 module.exports = {
  devServer: {
  port: 8081,
  // host: '0.0.0.0',
  headers: {
   'X-foo': '112233'
  },
  inline: true,
  overlay: true,
  stats: 'errors-only',
  proxy: {
   '/api': {
   target: 'http://127.0.0.1:3001',
   changeOrigin: true // Whether it is cross-domain
   }
  }
  },
 }

Because all the requests on my list.vue page are similar to this.$http.post(‘/api/query’, obj); therefore when I use /api/query to request, it will be Proxy to http://127.0.0.1:3001/api/query, so that the cross-domain problem can be solved. At the same time, we apply routing to app.js in the root directory of the project, with the following code:

 const addAndDelete = require('./database/addAndDelete');
 app.use('/api', addAndDelete);

When requesting http://127.0.0.1:3001/api/query, the /query interface method in addAndDelete.js will be automatically used.

View github code

The above is the entire content of this article. I hope it will be helpful to everyone’s study and I hope you will support me a lot.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/example-of-webpack4expressmongodbvue-implementing-addition-deletion-modification-and-query/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: 34331943@QQ.com

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索