Vue + Koa, directing a little practice

Function: based on vue koa mongodb login, registration, message simple website. Making: github.com/LiChangyi/d…

In front of the word

Update 12 September 2021: Due to cloud server expiration, the online Demo environment is no longer accessible.

why

  1. Some time ago, I set up a personal blog with vue+ KOa +mongodb. Because it was the first time to write the interaction before and after, I found that there were many parts that were not particularly perfect, and the code was not very readable for new scholars. So this little exercise, starting with a simple aspect, will hopefully give some inspiration to fellow travelers who have stepped on the same number of pits.
  2. When I studied VUE and KOA at the beginning of this year, the online content was a complete project, with too many files and too difficult to watch. Secondly, the uploading of pictures was not much involved.
  3. When I was learning to deploy koA and VUE projects, my online knowledge was patchy, so I’ll summarize it here.

Knowledge points involved

  1. Vue family barrel use
  2. Use axios in VUE and configure it
  3. Basic use of KOA and Mongoose
  4. Jsonwebtoken usage and front and back authentication login

Note: This article deals with the basics for those who are new to VUE or KOA or want to understand a simple front and back interaction problem.

preview

Questions of interest

I wrote a lot of comments in the code to facilitate reading, here is a simple talk about my personal original study when more confused for the problem

A few minor changes

The front end uses vuE-CLI directly for a basic project skeleton. Then because it is a simple project, so the page is written casually, mainly to achieve the function.

Since we are using a secondary domain name on the server, we need to set assetsPublicPath to a relative path in the build TAB under config/index.js.

assetsPublicPath: ' '
Copy the code

We need to debug in local development, need to use proxy, otherwise only set the background to allow cross-domain. So add the dev object under config/index.js:

proxyTable: {
    '/api': {// Proxies only requests under the/API URL
        target: "http://localhost:7778".// The address of the backend server
        changeOrigin: true}}Copy the code

How to make the server remember you (JsonWebToken)

HTTP requests are stateless, meaning they can’t remember who you are, they just know what resources you ask for and give you what. But the real problem is that when users ask us for resources, we should consider giving them resources. Make a determination of the person’s identity and then decide what resources to give him.

So for each user we need to use a unique identity to identify him, that is why we need to log in to operate, the purpose of login is to let the server to generate a recognition of your identity, you later every request to take up.

When there is no separation between the front and the back, the server will put a SessionId or a cookie on the client side. But now that we’ve logged in, the server should give us a string that uniquely identifies us. Then we take it with us every time we request data. Jsonwebtoken => server/utils/ toke. js and then I wrote a middleware check_token to determine if this resource needs to be logged in, I’m going to check his token and throw an error if his token isn’t correct.

After the front-end gets the token from the server, we need to store it in two ways:

  1. One drawback of this method is that the data in Vuex is wiped out as soon as the web page is refreshed. That means you have to log back in.
  2. Stored in sessionStorage, using the browser sessionStorage, only when the browser closed when the data will be cleared.

Here I combine the two methods. When I get the token, I store it in vuex and sessionStorage at the same time. Vuex is stored in vuex for convenient operation, and sessionStorage is stored in sessionStorage to keep the data not lost when refreshing the page. On the front end every time the request data to the background, take the token, as shown in the code = > client/SRC/axios/index. Js

About some of the online debates:

Q: Some people say that it is not safe to let the customer service store tokens, or to use the sessionStorage method to store tokens, because of the CSRF problem

A: There is no absolute security. I personally know that there are problems with cookies or sessionids in the past. To solve this problem, try to upgrade the web page to HTTPS, or, adopt the way of server transfer, add a server side between the two parties, store the real token in the transfer, and then the customer service side and the transfer to communicate.

Verification code identification

Verification code generated my gd – BMP was used to wrap the specific usage, see the server/controller/other. Js also based on the above introduction, HTTP is no status, we will verify the correctness of the authentication code, should be for each increase a unique identity authentication code, and stored in the data, When a user logs in or registers a verification code, the user sends the verification code and the corresponding verification code identifier to the background to check whether the verification code is correct. For the storage of verification code and identification, I use mongodb to store for convenience, but many people on the Internet recommend redis to store.

Upload local pictures

This problem from a long time ago very confused, do not know how to upload pictures to the server. Even if h5 , resolving this problem can be troublesome. Personally, I think there should be two ways to upload pictures:

  1. Upload binaries directly from the file retrieved from the onchang event on input.
  2. Convert the image to base64 for uploading

I use the second method here, upload the image with Base64, and then save the base64 string into the database, because the operation is more convenient. You can also convert base64 to a binary file on the server and store the file address in the database. It is also possible to upload binaries directly locally. If you do this, then you should include a middleware to handle file requests in the KOA.

I can also use third-party storage. For example, I wrote an interface in my blog that is to directly upload files to Qiuniuyun at the customer service terminal, and then Qiuniuyun returned the link to me. This was done because the small hose server was too slow and loading images with a third party was much faster.

Server deployment for the project

Because of the simplicity of Vue, many people only know NPM install and NPM run dev, so many people will have a question, that is, how do I deploy this VUE project on the server? Upload the code to the server to execute the above two commands?

In fact, this problem is caused by the fact that we only operate mechanically. Because of the simplicity of VUe-CLI and the strength of the MVVM framework, we forget that we write things on the notebook or the web. So we need to package our project with webpack and execute NPM run build on the command line to package our VUE and JS code and other resource files into /dist. The file here is the page we wrote, we just need to upload the file here to the server can run.

There are two ways to package files:

  1. Drop the file toserver/publicUnder the folder, because we’re inserver/app.jsNext we configure the static file directory, and then we start the server. Can be found at127.0.0.1:7778 / index. HTML(assuming the server port number is 7778) see our page.
  2. Using the Nginx server proxy, static files are hosted by Nginx, and then set up a forwarding mode to get the API request data.

In fact, the first way is also with nodeJS will automatically start a server, hosting static files. I personally prefer the second method, so let’s configure this file.

Before you start, you should check whether your server has Nginx and PM2 installed

$ pm2 -v
$ nginx -v
Copy the code

If the correct version number appears, it is already installed, if not, please Google install. Pm2 is the process daemon that restarts your NodeJS when it unexpectedly stops.

If we have a domain name, we now have a domain name provider where to add a secondary domain name resolution. There is a wait of a few minutes after the parsing is added

Then, we go to the nginx configuration file nginx.conf and add:

server { listen 80; server_name www.a.com; root /data/www/demo; index index.html index.htm index.php; location /api/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; Proxy_pass http://127.0.0.1:7778; }}Copy the code

Note: location/API/indicates that only API /* requests are forwarded.

Then do the nginx server restart: nginx -s reload

We put the server code under the server and use the command line to move to the corresponding location to execute the command:

$ npm install && cnpm i
$ pm2 start --name demo1 npm -- run start
Copy the code

Start our NodeJS server. Then we can go to the website and see the effect

The last

As a result of my talent, if there are any questions welcome to discuss the following message!