preface

Hi, everyone, I am Mai Shu, today to bring you the use of Ali cloud server deployment of the front and back end separation project. Recently I bought an Ali cloud server and domain name, and then I put it there (I don’t know why I bought it, hahaha)! Just to catch up with the company’s new project online, the boss asked me to deploy the front and back end separation project, let’s use him to conduct a drill deployment!

By the end of this article, you will have mastered the use of Nginx as a proxy and cross-domain processing, if deployed on two servers before and after the separation of projects. If there is a need later, it is recommended to collect, really will step on a lot of pits.

Do you need to prepare?

Here is an account of my environment

  • Two AliYunECSServer: Server A deploys the front-end project. Server B deploys the back-end project
  • Vue 2.6.10
  • Spring Boot 2.2.4. RELEASE

Ii Project packaging

2.1 Front-end Projects

Our front-end project is developed using VUE, and in the package.json file of the front-end project, scripts for packaging are typically defined

Package by entering the command NPM run build:sit on our developer console

When we finished packing, dist directory will appear under our project directory, which stores the files we packed

2.2 Back-end projects

Our back-end project is developed by Spring Boot + Maven. Please note that clean->install will be successfully packaged under the parent project (root)

The completed package file is located in the target directory, and the xxxxx.jar file is the one we will deploy

3 Project Deployment

Here I use Ali cloud server for deployment, front-end projects and back-end projects will be deployed to different servers, through nGINx for proxy and cross-domain processing

The server Deployment project The environment
Server A The front-end project nginx
Server B The back-end project nginx+jdk8

If your server is being deployed for the first time, you may need to install JDK, mysql, Redis, etc

3.1 Enabling ECS Server Ports

First, log in ali Cloud to the ECS console of cloud server, click security group —-> Configure rules

You can click Manual add add rules: you can fill in the following red box configuration

Why do I need to enable the port?

Because I will install the nginx listening port needs to be configured as 8081, ali cloud server needs to be enabled in the background, otherwise Nginx cannot listen

3.2 Installing Nginx in Linux

Both servers A and B need to have Nginx installed, primarily as A project agent. Refer to another article of mine

3.3 Deploying front-end Projects

Log in to server A and create A folder. Generally, I create A data directory under the root directory and divide the data directory by project name, for example :/data/ Milogenius/Upload the packaged front-end project dist directory

Server A nginx configuration, listening port number is just we opened 8081

The only thing you need to change is the absolute path after 8081 / Web Alias

server {
        listen       8081;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/access.logmain; location /web { alias /data/milogenius/dist; index index.html; }}Copy the code

Note: Server A only needs to configure the front-end project agent, back-end project agent does not need to configure, because the front-end project is deployed on different servers, in the front-end project request back-end interface, do not go to the front-end server

3.4 Deploying back-end Services

Log in to server A and create A folder. Generally, I create A data directory under the root directory and classify the data directory by project name, for example, /data/milogenius/ upload the packaged jar package of the back-end project

Start the JAR package and replace XXXX with your own name

nohup java -jar xxxxx.jar >./xxxxxx.log 2> &1 &
Copy the code

The configuration of nginx in server B, listening port number is 8081,9888 is the port that our back-end project starts. Here we use NGINx to handle cross-domain problems uniformly

You need to change the port number :8081 / API proxy_pass to the configuration of your own project

server {
        listen       8081;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/access.log  main;

       location /api {
                        if ($request_method = 'OPTIONS') {
                                add_header 'Access-Control-Allow-Origin' '$http_origin';
                                add_header 'Access-Control-Allow-Credentials' 'true';
                                add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
                                add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Age nt,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,token';
                                add_header 'Access-Control-Max-Age' 1728000;
                                add_header 'Content-Type' 'text/plain charset=UTF-8';
                                add_header 'Content-Length' 0;
                                return 204;
                }
                        add_header 'Access-Control-Allow-Origin' '$http_origin';
                        add_header 'Access-Control-Allow-Credentials' 'true';
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
                        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X -Requested-With,If-Modified-Since,Cache-Control,Content-Type,token';
                        proxy_pass http://localhost:9888;
                        client_max_body_size 1024m; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; }}Copy the code

Four cross domain processing

Cross-domain issues must be addressed in a back-end separation project. We have already configured a unified cross-domain solution in NGINX when we first deployed the back-end project. Let’s take a look at this area

4.1 What is Cross-domain

The same origin policy is restricted by the browser. The Sameoriginpolicy is a convention. It is the core and basic security function of the browser. If the Sameoriginpolicy is missing, the normal functions of the browser may be affected. The Web is built on the same origin policy, and browsers are just an implementation of the same origin policy. The same origin policy prevents javascript scripts in one domain from interacting with content in another domain. Same-origin (that is, in the same domain) means that two pages have the same protocol, host, and port.

When the protocol, domain name, or port of a URL request is different from the current page URL, it is called cross-domain

Current page URL Url of the requested page Whether the cross-domain why
www.test.com/ www.test.com/index.html no Same-origin (same protocol, domain name, and port number)
www.test.com/ www.test.com/index.html Cross domain Different protocols (HTTP/HTTPS)
www.test.com/ www.baidu.com/ Cross domain Different master domain name (test/baidu)
www.test.com/ blog.test.com/ Cross domain Different subdomains (WWW /blog)
www.test.com:8080/ www.test.com:7001/ Cross domain Different port numbers (8080/7001)

4.2 Cross-domain Solution

1 Java backend global configuration

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter(a) {
        CorsConfiguration config = new CorsConfiguration();
          config.addAllowedOrigin("*");
          config.setAllowCredentials(true);
          config.addAllowedMethod("*");
          config.addAllowedHeader("*");
          config.addExposedHeader("*");


        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/ * *", config);


        return newCorsFilter(configSource); }}Copy the code
@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter  {


  @Override  
    public void addCorsMappings(CorsRegistry registry) {  
        registry.addMapping("/ * *")  
                .allowCredentials(true)  
                .allowedHeaders("*")  
                .allowedOrigins("*")  
                .allowedMethods("*"); }}Copy the code

The Controller method is annotated CrossOrigin,origin=”*” to indicate that all domain names are accessible

@RequestMapping("/tet")
@CrossOrigin(origins = "*",maxAge = 3600)
public String test( ){
  return "This method supports cross-domain requests!!";
}
Copy the code

2 Vue-CLI project Webpack agent to solve the cross-domain problem, add the following code to vue.config.js file

// Generate a proxy configuration object that can be configured with multiple proxy addresses
let proxyObj = {
    '/test': {
        target: "http://localhost:8080"
    },
    '/test2': {
        target: "http://localhost:8081"}};module.exports = {
    baseUrl: '/'.outputDir: 'dist'.lintOnSave: false.runtimeCompiler: true.devServer: {
        contentBase: ". /".port: 8080.disableHostCheck: true.proxy: proxyObj,
        before: app= >{}}}Copy the code

JQuery ajax JSONP solves cross-domain problems

$.ajax({  
        type : "get".async:false.url : "http://localhost:8080/test".dataType : "jsonp".// The data type is jsonp
        jsonp: "jsonpCallback".// The server returns the callback method name
        success : function(data){  
            alert(JSON.stringify(data));
        },  
        error:function(){  
            alert('Request error! '); }});Copy the code

4 Nginx global processing

The last one is the nginx configuration we are using,

       location /api {
                        if ($request_method = 'OPTIONS') {
                                add_header 'Access-Control-Allow-Origin' '$http_origin';
                                add_header 'Access-Control-Allow-Credentials' 'true';
                                add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
                                add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Age
                                nt,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,token';
                                add_header 'Access-Control-Max-Age' 1728000;
                                add_header 'Content-Type' 'text/plain charset=UTF-8';
                                add_header 'Content-Length' 0;
                                return 204;
                }
                        add_header 'Access-Control-Allow-Origin' '$http_origin';
                        add_header 'Access-Control-Allow-Credentials' 'true';
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
                        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X
                        -Requested-With,If-Modified-Since,Cache-Control,Content-Type,token';
                        proxy_pass http://localhost:9888;
                        client_max_body_size 1024m;
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header Host $host;
                        proxy_redirect off;
                }
Copy the code

Iv Visit Items

Now we access the front-end project and use the address http:// server A external IP address :8081/web, and find the following error

Access to XMLHttpRequest at 'http://ip address: 8081 / API/login' from origin 'http://ip address: 8081' has been blocked by CORS policy: Request header field tenant_code is not allowed by Access-Control-Allow-Headers in preflight response.
Copy the code

We can see that tenant_code in the request header is not allowed to allow our front-end project to access the back-end project, so we need to add this request header to nginx in server B

add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,token,tenant_cod e';
Copy the code

After the configuration is complete, restart nginx and retry. The following error occurs

The 'Access-Control-Allow-Origin' header contains multiple values 'http://ip :8081, http://ip :8081', but only one is allowed.app07.bc0251.js:1 Error: Network Error
Copy the code

As you can see, we have configured cross-domain processing twice. Since we are handling cross-domain issues uniformly through Nginx, we need to comment out the configuration in the back-end code

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/ * *")
            .allowedOrigins("*")
            .allowCredentials(true)
            .allowedMethods("GET"."POST"."PUT"."DELETE"."OPTIONS")
            .maxAge(3600); }}Copy the code

After redeploying the project, we revisited and found that it was normal

That’s the end of the article. Thank you for reading

Copy the code