AJAX and axios framework


foreword

提示:这里可以添加本文要记录的大概内容:

Front-end and back-end interaction through ajax
Please add a picture description

the case

This project uses javaweb knowledge

First create a JavaWeb project to write code:

package ajax;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

@WebServlet("/ajax")
public class ajax extends HttpServlet {
    
    

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        // 将Gson库放在WEB-INF/lib目录下
        // 运行时加载Gson库
        try {
    
    
            Class.forName("com.google.gson.Gson");
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
            return;
        }

        List<User> list = new ArrayList<User>();
        list.add(new User(1,"张三","23"));
        list.add(new User(2,"李四","28"));
        Gson gson = new Gson();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(gson.toJson(list));
    }

    class User {
    
    
        private int id;
        private String name;
        private String age;

        public User(int id, String name, String age) {
    
    
            super();
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public int getId() {
    
    
            return id;
        }

        public void setId(int id) {
    
    
            this.id = id;
        }

        public String getName() {
    
    
            return name;
        }

        public void setName(String name) {
    
    
            this.name = name;
        }

        public String getSex() {
    
    
            return age;
        }

        public void setSex(String sex) {
    
    
            this.age = age;
        }
    }
}
//最后将Gson库的jar包重新复制到WEB-INF/lib目录下,或者在Java Web项目的classpath中添加Gson库的jar包

operation result:
insert image description here

Next create a vue project

After creating the project, go to install the Axios frameworknpm i axios

Open the root component, delete all code and regenerate

Add a button inside the template tag

<!-- 看到按钮就想到事件 -->
<button @click="send">发送请求</button>

Next, configure the method in methods

  methods: {
    
    
    send(){
    
    
    
  },

To axiossend a request with a frame, you first need to scriptimport the frame in the tag

// 第一个axios是自定义名字
import axios from 'axios'

Now back sendinside the method, import the axios call

  methods: {
    
    
    send(){
    
    
      // get方法代表向后端发送请求   参数是后端项目程序地址
      // then方法代表处理后端发送回的响应数据
      axios.get('http://localhost:8888/ajax/ajax')
      .then( (resp)=>{
    
    
      //log测试
        console.log(resp.data);
      } )
    }
  },

localhost is the local address, you can also write your own IP address.
After running the code, right-click the developer mode and click the console, and then click the send request button:insert image description here

cross domain access

The purpose of the proxy server: the
main purpose of the proxy server is to provide a way for the client to indirectly access online resources. The client sends a request to the proxy server, and the proxy server automatically forwards it, thereby completing the request and response instead of the client.

For the understanding of the proxy server, you can refer to the following metaphor: Suppose you need to visit a website, but for some reason you cannot directly connect to the website, then you can use a proxy server to help you connect to the website. A proxy server is like a middleman, it receives your request, then forwards the request to the target website, and then returns the response of the target website to you.
This process is like a postman. He receives the request from the user, forwards the request to the target server, and returns the response to the user after the target server responds. This process is like a person who needs to send a letter to another person, but for some reason it cannot be sent directly, so it needs to be sent to the postman, and the postman will help deliver it to another person. Proxy servers can improve access speed, protect privacy, filter content, and more.
Therefore, a proxy server can help you bypass some restrictions and policies in some specific cases, so as to achieve the purpose of accessing the target website.

There is a vue.config.js file at the bottom of the project, and the proxy server is added (after the third line)

  devServer: {
    
    
    proxy: {
    
    
      '/api':{
    
    
        target: 'http://localhost:8888/ajax/',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
    
    
          '^/api':''
        }
      }
    }
  }

At this time, go back to the root component, and the address sendin the method axiosshould be changed to the proxy server address

      axios.get('/api/ajax')  

Restart the project , refresh the page, and click the button:
insert image description here

Next, improve the project, because in the actual project, the user will not look at the console,
the data should be sent back and rendered to the view

Make a configuration item in data, and assign the response data sent back to the configuration data in data. As soon as the value is assigned, vue will listen to it, and the data will change. Immediately modify the data and synchronize it to the view

  data () {
    
    
    return {
    
    
       // 返回到数据是个数组,包含多个数据
       arr:[]
    }
  },

Next, delete the log output in the send method of the label in methods, and add

//等于发送回来的相应数据
this.arr = resp.data

Improve the html code, add a table here

<template>
  <div>
    <!-- 看到按钮就想到事件 -->
    <button @click="send">发送请求</button>
    <table>
      <tr>
        <th>id</th>
        <th>名字</th>
        <th>年龄</th>
      </tr>
      <tr v-for="(item, index) in arr" :key="index">
        <th>{
   
   { item.id }}</th>
        <th>{
   
   { item.name }}</th>
        <th>{
   
   { item.age}}</th>
      </tr>
    </table>
  </div>
</template>

Add css style:

<style scoped>
table {
    
    
  border-collapse: collapse;
  width: 100%;
  margin-top: 50px;
}

th, td {
    
    
  border: 1px solid black;
  padding: 8px;
  text-align: center;
}

thead {
    
    
  background-color: #f2f2f2;
}

tr:nth-child(even) {
    
    
  background-color: #f2f2f2;
}

button {
    
    
  margin-bottom: 20px;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  background-color: #4CAF50;
  color: white;
}
</style>

running result:

insert image description here

Summary❗

Same-origin policy for asynchronous requests:
the request sent by the browser must have the same IP address and port number as the front-end server

The front-end and back-end separation projects use the Ajax asynchronous request communication method and
use the axios framework to send asynchronous
requests. When the browser sends an Ajax request, there will be restrictions on the same-origin policy, which prohibits cross-domain requests.
The protocol, IP address, and port number of the front-end and back-end projects are the same.

Cross-domain request solution:
1. Configure a proxy server in the front-end project (high security, commonly used)
2. Set the response header to resource sharing status in the back-end project (high risk)

Supongo que te gusta

Origin blog.csdn.net/rej177/article/details/131691736
Recomendado
Clasificación