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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment