search
HomeWeb Front-endJS TutorialHow 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
nginxvue.jsSeparation 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;
       }
    })

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>

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>

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 id="Yes">Yes</h1>

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

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; 
    }  
  }

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();
    }

  }

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);
       });
    });

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
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment