vue
element
mongodb
express
rendering
preface
Recently I have been wanting to learn node, after all, node’s front-end is more marketable. However, I still felt that something was missing, so I went to Github to see other people’s projects and learned a lot, so I decided to write one myself.
As programmers, we must keep learning so that we can have a place in the workforce.
I believe that when I go out to interview, I will be asked questions not only about HTML, CSS, javascript, jQuery, but also about various frameworks (Vue, Angular, React), server languages (Java, Node), databases, ES6 new features, etc.
If you’re not sure how to quickly build a project skeleton using vue-CLI, check out my article on how to build a single page application using VUe-CLI, WebPack, Vue-Router, vue-Resource
If you’re still in the same place, standing still. Then I bet you’re going to be out.
Before I dive into this article, I want to tell you what you’ll get out of it!
Learning about Vue, you will know that there are more convenient data drivers besides jQuery’s structural drivers (manipulating DOM elements), and mom will no longer have to worry about me forgetting the horrible selectors in jQuery. Learning Node, you will know that in addition to Java, C, Python these strange background language, js since can also write background, you can define their own interface, do not rely on those background rough man. Learn how to store data in a database and how to add, delete, or insert data.
With all that said, I think you already know. Right! Yes, this will be your way to the full stack. It’s exciting to think about it. So, let’s move on to the main body.
Suggestion: You can go to my Github project address to clone a copy of my code to the local, follow my ideas to go through, I believe that after reading, you will be more confident about yourself. There will be detailed comments in the code that will clear up a lot of your confusion. If you get something from this article, don’t forget to move your cute little hands and give it a star.
The body of the
There are many details in the article, will not say too fine, if the encounter threshold, you can baidu, encounter difficult to understand the place, I will be emphasized.
The development environment
Mongodb, NodeJS, vuE-CLI (scaffolding)
Step 1: Initialize the project
With vue-CLI scaffolding, we can quickly build a project skeleton.
vue init webpack my-project
cd my-rpoject && npm install
cnpm run dev
Copy the code
If you see the following figure on the terminal, the project has started successfully. Then type localhost://8080 in your browser’s address bar. If you see vue’s welcome screen, you have completed step 1.
Step 2: Start local mongodb
Prerequisite: Downloadmongodb
And the environment variables have been configured.
If setting environment variables is a hassle, you can use Homebrew for a one-click installation.
When all is said and done, simply go to the mongodb installation directory (for example, my mongodb installation directory is /usr/local/bin/) and run the mongo command. If you can see the image below, you have completed step 2.
Step 3: Write the background interface well
Note: the so-called background interface, is through express to establish routing, if you do not understand the express can see the introduction of expressExpress website.
Prerequisites: The Express, Mongoose, and body-Parser modules are installed through NPM
The Express module is used to create routes and the Mongoose module is used to create databases. The connection database body-Parser module is used to parse the request body of POST requests
// Enter the project from the command line and run the following command to install the three modules
cnpm install express body-parser mongoose --save
Copy the code
Create an app.js file in the project root directory to start the Express service
/ / app. Js file
1. Import the Express module
const express = require('express')
//2. Create an app object
const app = express()
// Define a simple route
app.use('/',(req,res) => {
res.send('Yo! ')})// Define the service startup port
app.listen(3000, () = > {console.log('app listening on port 3000.')})Copy the code
After the preceding steps are complete, run node app.js on the command line. Use a browser to access localhost:3000. If res.send () is displayed on the page, it indicates success.
Step 4: Create the data model
Tip: The so-called data model can be understood as what kind of data fragments and data types you want to store in the table you create in the future.
Create a models folder in the project root directory to store the data models. Each model is produced by a Schema. We don’t have to worry about the details.
Create a hero.js file in the Models folder with the following contents
/ / hero. Js file
// Introduce mongoose module
const mongoose = require('mongoose')
// Select * from table_name; // Select * from table_name; // Select * from table_name
const heroSchema = mongoose.Schema({
name :String.age : String.sex : String.address : String.dowhat : String.imgArr: [].favourite:String.explain:String
}, { collection: 'myhero'})
// Mongoose. Schema should specify which table in the database to fetch data from. Myhreo is used for future operations on myhreo.If you don't write the second argument here, you'll get a pit later.// Export the model module
const Hero = module.exports = mongoose.model('hero',heroSchema);
Copy the code
Step 5: Create CURD(Add, Delete, modify, search) routing interface
Create a router folder in the root directory of the project, and create a hero.js file in the folder with the following contents: add, delete, modify, search, add images, etc
// Introduce the Express module
const express = require("express");
// Define routing level middleware
const router = express.Router();
// Introduce the data model module
const Hero = require(".. /models/hero");
// Query all hero routes
router.get("/hero", (req, res) => {
Hero.find({})
.sort({ update_at: - 1 })
.then(heros= > {
res.json(heros);
})
.catch(err= > {
console.log(2);
res.json(err);
});
});
Query the route information about a single hero through ObjectId
router.get("/hero/:id", (req, res) => {
Hero.findById(req.params.id)
.then(hero= > {
res.json(hero);
})
.catch(err= > {
res.json(err);
});
});
// Add a hero message route
router.post("/hero", (req, res) => {
// Use the create method on the Hero Model to store data
Hero.create(req.body, (err, hero) => {
if (err) {
res.json(err);
} else{ res.json(hero); }}); });// Update a hero data route
router.put("/hero/:id", (req, res) => {
Hero.findOneAndUpdate(
{ _id: req.params.id },
{
$set: {
name: req.body.name,
age: req.body.age,
sex: req.body.sex,
address: req.body.address,
dowhat: req.body.dowhat,
favourite: req.body.favourite,
explain: req.body.explain
}
},
{
new: true
}
)
.then(hero= > res.json(hero))
.catch(err= > res.json(err));
});
// Add image routing
router.put("/addpic/:id", (req, res) => {
Hero.findOneAndUpdate(
{ _id: req.params.id },
{
$push: {
imgArr: req.body.url
}
},
{
new: true
}
)
.then(hero= > res.json(hero))
.catch(err= > res.json(err));
});
// Delete a hero route
router.delete("/hero/:id", (req, res) => {
Hero.findOneAndRemove({
_id: req.params.id
})
.then(hero= > res.send(`${hero.title}Delete succeeded '))
.catch(err= > res.json(err));
});
module.exports = router;
Copy the code
Finally, apply the route to app.js(import the route definition in app.js)
/ / app. Js file.// Import the hero route just defined
const hero = require('./router/hero')... app.use('/api',hero)
......
Copy the code
At this time you can use Postman (simulated HTTP request data software) query test, if you can query the data, on behalf of the background interface has been successfully written
Note: before querying, you need to learn how to add any data to the corresponding table in mongodb. Otherwise, your query will be empty!!
For example, if I create a myHero table above, I will add a mock data to the table before executing the query above
//db.myhero.insert means to add a data item to the database table named myhero
db.myhero.insert({
"imgArr" : [
"http://ossweb-img.qq.com/images/lol/web201310/skin/big157000.jpg"."http://ossweb-img.qq.com/images/lol/web201310/skin/big157001.jpg"."http://ossweb-img.qq.com/images/lol/web201310/skin/big157002.jpg",]."name" : "The line"."age" : "22"."sex" : "man"."address" : "Demacia"."dowhat" : "Medium single, Assassin."."favourite" : "Death follows me like the wind."."explain" : "Yasuo was an indefensible Ionian and a swift swordsman, able to wield the power of the wind against his enemies. As a young man, he repeatedly lost precious things to honor, his position, his mentor, and finally his own brother. He was ruined by the suspicion he could not shake off and was now a wanted criminal. Yasso roams the land of his home in search of redemption from his past. The wind alone guided his sword.,})Copy the code
Here for database operations, can be carried out in the terminal, you can also download the visual tool Robo 3T(link address) to operate, will be more convenient.
Ok, so here we have the complex part of the whole functionality implemented. Let’s review what we’ve done to prepare
- through
vue-cli
Initialize the project - Start the local mongodb service
- Write the background interface route
app.js
file - Create the data model where we hold the data
heroSchema.js
file - Write add, delete, change and search route interface
hero.js
file
With a bang, it’s the front end that we’re good at. Now you can breathe a little easier. Do you feel very exciting, very satisfying ~
Step 6: Select the necessary modules for front-end development
Tip: this is free to play, I downloaded the module element, vue-resource. I recommend that you use the same modules as I do, so that you don’t have to worry about it later, so that when you come back and you know the whole project, you can choose what technology you want to use,
// Element-UI is a componentized framework provided by Ele. me for our front-end developers. Good enough to have no friends. Vue-resource is used to handle requests, but after Vue2.0, there seems to be an Axios that does not maintain vue-Resource, but I used vue-resource all the time, which is very convenient and can still use it.
cnpm install element-ui vue-resource --save
Copy the code
Step 7: Set up the home page and detail page components
In the SRC /components path, create two pages: list. vue(home page) and detail. vue(details page).
Create a router folder in the SRC directory. Create an index.js front-end routing file in the router folder
The front-end routing file index.js contains the following contents
// Routing page
import Vue from 'vue'
// Import the routing module and check the terminal. If the terminal displays a message indicating that the VUe-Router module is not installed, install it
import Router from 'vue-router'
// Introduce the List and Detail components respectively
import List from '@/components/List'
import Detail from '@/components/Detail'
Vue.use(Router)
// Define routes that are mapped to the
viewport of app. vue
export default new Router({
routes: [{path: '/'.name: 'List'.component: List
},
{
path : '/league/:name'.name : 'Detail'.component : Detail
},
]
})
Copy the code
Step 8: Handle cross-domain cases
Because our Express service is started on port localhost:3000, and our vue-CLI created project is started on the default port 8080, cross-domain situations are definitely involved
The good news is that VUE-CLI provides us with a configuration portal to resolve cross-domain issues
Js file under the config directory in the root directory. There is a configuration item proxyTable in the file
At this time, when we are in the front with the vue – resource access/API, will be acting to http://localhost:3000/api, so as to obtain the data you need. Basically, it’s a transition job.
Step 9: Build the page
At this point, all the preparatory work is done and we can write the front-end code. I won’t say much about layout. The interaction aspect is mainly to define a series of methods in the methods option of VUE, and bind the methods to the corresponding place by **@click=” XXX “** method. The specific method definition can be seen in the code I wrote.
The end
Once the project is written, it is packaged and the packaged dist folder is used as the directory for the Express static file service.
cnpm run build
Copy the code
app.use(express.static('dist'))
Copy the code
Finally, take a look at the directory structure of the entire project
Welcome friends to put forward their own opinions, and point out the mistakes in the article 😊
If this article has given you some help.why don’t give me a star✨!
Portal: Personal blog