Home Web Front-end JS Tutorial How to achieve front-end and back-end separation in nginx+vue.js

How to achieve front-end and back-end separation in nginx+vue.js

Jun 06, 2018 am 09:43 AM
nginx vue.js Separation of front and back ends

This article mainly introduces the sample code of nginx vue.js to achieve front-end and back-end separation. Now I will share it with you and give you a reference.

1.nginx is a high-performance HTTP and reverse proxy server, often used for distributed server management.

It is often used for load balancing (this is achieved by calling multiple servers)

Static resource output is faster, and the resource can be gzip compressed and output (this is also an important reason why this article uses it for static resource access)

Suitable for solving cross-domain problems and reverse Proxy (because no one wants to see access to other domain names under this domain name, cross-domain can lead to CSRF attacks, this is the second reason for using it in this article)

takes up less memory and takes seconds Start, can quickly switch nodes to prevent downtime

2.es6 is the sixth version of ECMAScript. If you want to learn js frameworks such as vue.js, this is a language that must be learned. It is recommended The learning address is as follows: http://es6.ruanyifeng.com/

3.vue.js is a front-end template rendering engine, similar to the back-end jsp, beetl and other template engines. Of course, it can also be combined with the node environment Used as back-end rendering. (The official website has supported it)

Having said the above points, let us answer a few whys?
1. What are the benefits of realizing front-end and back-end separation? What are the main application scenarios? ?
2. Why do you need to use a front-end template engine when you have a back-end template engine? What are their advantages and disadvantages?
3. What changes need to be made to achieve front-end and back-end separation?

After thinking about the long dividing line………………

1. First of all, look at the problem from a development perspective. Most of the previous projects were PC-side projects. , and the scene is simple and fixed. Most of the requests are stateful. Now we often have more mobile projects, and most of the same apps are a combination of native and embedded pages. And now the project scenes are more diverse, This results in a functional module that is likely to be the result of requests from several projects.

2. If we still follow the previous practice, the first problem is that I can only use jsonp to solve the problem of adjusting multiple cross-domain The problem with the request is that the code is too redundant to implement. For the same function, it is very likely that there are two different writing methods on the app side and the PC side. And bandwidth is a very expensive thing. The client always goes to the server to request static resources, which will cause slow speed. Dynamic and static separation can achieve separate acquisition of static resources and dynamic resources, and the server can also separate dynamic and static resources, effectively solving the bandwidth problem.

3. Back-end developers may not be as proficient in css and js as the front-end. For example, when using jsp to fill in data, back-end developers are often required to adjust styles and write js, which will cause low development efficiency.

4. Using front-end template rendering can release part of the pressure on the server side, and the front-end template engine supports more functions than the back-end. For example, you can use vue to customize components, verification methods, in-depth gradients, etc., which is better than The back-end template engine needs to be more functional.

4. Our solution is as follows

1. Traditional interaction method:

Client initiated Request, server-side response, dynamic data is generated through a series of operations, and the dynamic data is handed over to the back-end template engine. After rendering, it is passed to the front-end.

2. Improved interaction method

The client initiates a request and nginx intercepts it. If it is a static resource, it is directly compressed by the file server and sent to the front end. If it is a dynamic resource request, dynamic data is generated through the dynamic resource server, returned to the front end in json format, and handed over to vue.js Display after rendering.

5. Explanation of the key functions of vue.js version 2.x

1. How to bind to the html structure and how to bind it to the style For dynamic binding, what are the commonly used monitoring events?

1.Basic rendering

    //html结构
    <p id="app">
     {{ message }}
    </p>

    //js模块
    var app = new Vue({
    //会检索绑定的id 如果是class 则是.class即可绑定
       el: &#39;#app&#39;,
       data: {
        message: &#39;Hello Vue!&#39;
       }
    })
Copy after login

2.Class and style binding

<p class="static"
  v-bind:class="{ active: isActive, &#39;text-danger&#39;: hasError }">
</p>

 data: {
     isActive: true,
     hasError: false
    }

渲染结果为:<p class="static active"></p>
Copy after login

3.Commonly used binding events

 //输出html
<p v-html="rawHtml"></p>
//绑定id或class
<p v-bind:id="dynamicId"></p>
//绑定herf
<a v-bind:href="url" rel="external nofollow" ></a>
//绑定onclick
<a v-on:click="doSomething"></a>
Copy after login

2. How to communicate with the server

It is recommended that you use axios to make requests to the server, and then hand over the requested data to vue.js for processing.

About axios usage example link address

3. Common process control statement data verification custom instructions

 //if 语句
 <h1 v-if="ok">Yes</h1>

 //for 循环语句
 <ul id="example-1">
 <li v-for="item in items">
  {{ item.message }}
 </li>
 </ul>
Copy after login

Data verification and its form control binding link address (https:// cn.vuejs.org/v2/guide/forms.html)

The following four points refer to the official website API and will not be introduced again

4. How to implement in-depth responsiveness (for the first time After the page is initialized and filled with values, what should I do if there are changes?)?

5. Custom component application and its use of Render to create Html structure

6. The use of routing

7. Common modifiers

6. Practical examples

1.nginx configure static resources

 server {
    listen    4000;
    server_name www.test.com;
    charset utf-8;
    index /static/index.html;//配置首页

    //这边可使用正则表达式,拦截动态数据的请求,从而解决跨域问题
    location = /sellingJson.html {
      proxy_pass http://192.168.100.17:8090/vueHelpSellingcar.html;
    }

    #配置Nginx动静分离,定义的静态页面直接从static读取。
    location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ 
    { 
    root /static/;
    #expires定义用户浏览器缓存的时间为7天,如果静态页面不常更新,可以设置更长,这样可以   节省带宽和缓解服务器的压力
    expires   7d; 
    }  
  }
Copy after login

2. Backend request returns json data (take java as an example)

  @RequestMapping("/vueHelpSellingcar.html")
  public void vueHelpSellingcar(HttpServletRequest request,HttpServletResponse response) {
    //若干操作后,返回json数据
    JSONObject resultJson = new JSONObject();

    resultJson.put("carbrandList", carbrandList);
    resultJson.put("provinceList", provinceList);

    //进行序列化,返回值前端
    try {
      byte[] json =resultJson.toString().getBytes("utf-8");
      response.setHeader("Content-type", "text/html;charset=UTF-8");
      response.getOutputStream().write(json);
    } catch (Exception e) {
      e.printStackTrace();
    }

  }
Copy after login

3. Front-end call vue example

//html模块
  <p v-if="carbrandList.length" class="char_contain">
   <p v-for="brand in carbrandList" id="  {{brand.brand_id}}">{{brand.brand_name}}</p>
  </p>

//js模块 页面加载后,自动去获取动态资源
  let v={};
  $(function() {
    axios.get(&#39;http://test.csx365.com:4000/sellingJson.html&#39;)
      .then(function(data){
        //定义一个vue对象,方便模板渲染
        v =Object.assign(v, new Vue({
        el : &#39;.char_contain&#39;, //绑定事件名
        data : {
           carbrandList : data.data.carbrandList, //数据流
         }
        })); 
       })
       .catch(function(err){
         console.log(err);
       });
    });
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to achieve intermittent text cycle scrolling effect through JS

Detailed explanation of refs in React (detailed tutorial)

Use tween.js to implement the easing tween animation algorithm

The above is the detailed content of How to achieve front-end and back-end separation in nginx+vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure cloud server domain name in nginx How to configure cloud server domain name in nginx Apr 14, 2025 pm 12:18 PM

How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

How to check nginx version How to check nginx version Apr 14, 2025 am 11:57 AM

The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

How to start nginx server How to start nginx server Apr 14, 2025 pm 12:27 PM

Starting an Nginx server requires different steps according to different operating systems: Linux/Unix system: Install the Nginx package (for example, using apt-get or yum). Use systemctl to start an Nginx service (for example, sudo systemctl start nginx). Windows system: Download and install Windows binary files. Start Nginx using the nginx.exe executable (for example, nginx.exe -c conf\nginx.conf). No matter which operating system you use, you can access the server IP

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

How to check whether nginx is started How to check whether nginx is started Apr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to run nginx apache How to run nginx apache Apr 14, 2025 pm 12:33 PM

To get Nginx to run Apache, you need to: 1. Install Nginx and Apache; 2. Configure the Nginx agent; 3. Start Nginx and Apache; 4. Test the configuration to ensure that you can see Apache content after accessing the domain name. In addition, you need to pay attention to other matters such as port number matching, virtual host configuration, and SSL/TLS settings.

How to create a mirror in docker How to create a mirror in docker Apr 15, 2025 am 11:27 AM

Steps to create a Docker image: Write a Dockerfile that contains the build instructions. Build the image in the terminal, using the docker build command. Tag the image and assign names and tags using the docker tag command.

How to start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

See all articles