Problems with cross-domain requests

  • Problem specification
  • The solution

Problem specification

The same origin policy is an important security policy that restricts how an Origin document or the scripts it loads can interact with resources from another source. It can help block malicious documents and reduce the number of vectors that can be attacked. But sometimes we run into cross-domain requests when we want to access. Here’s a solution.

Front-end table code that requires access to back-end data:

<template>
    <div>
        <el-table :data="tableData" style="width: 100%" size="mini">
             <el-table-column
                    prop="name"
                    label="Show the name directly"
                    width="180">
            </el-table-column>

            <el-table-column label="Date" width="180">

                <template slot-scope="scope">
                    <i class="el-icon-time"></i>
                    <span style="margin-left: 10px">{{ scope.row.date }}</span>
                </template>

            </el-table-column>



            <el-table-column label="Name" width="180">
                <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                        <p>{{scope.row.name}}</p>
                        <p>{{scope.row.address}}</p>
                        <div slot="reference" class="name-wrapper">
                            <el-tag size="medium">{{ scope.row.name }}</el-tag>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>

            <el-table-column label="Operation">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">The editor</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">delete</el-button>
                </template>
            </el-table-column>
        </el-table>




    </div>
</template>

<script>
    import axios from  'axios'
    export default {
        name: 'Table'.components: {},data() {
            return {
                tableData: []}},methods: {},created() {  // Look here, look here, look here !!!!!
			
			// Request data from the back end. If the back end does not process the data, it will encounter cross-domain request problems
			axios.get('http://127.0.0.1:8080/web/user')
			
			// Write dead JSON data in the front end to test access
            // axios.get('stu.json')
             .then((res) = >{
                 this.tableData = res.data
             })
              .catch(function (error) {
                console.log(error); }); }}</script>

<style>
</style>
Copy the code

The code for created() in the front-end table:

created() {
			
	// Request data from the back end. If the back end does not process the data, it will encounter cross-domain request problems
	axios.get('http://127.0.0.1:8080/web/user')
	
	// Write dead JSON data in the front end to test access
	         // axios.get('stu.json')
	          .then((res)=>{
	              this.tableData = res.data
	          })
	           .catch(function (error) {
	             console.log(error);
	           });
	
	
	 }
Copy the code

Back end UserController code:

package com.neuedu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.neuedu.entity.User;

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 java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Keafmd
 *
 * @ClassName: UserController
 * @Description: UserController
 * @author: Conan the cow@dateHe: 2020-12-17 * * * * / http://127.0.0.1:8080/web/user

@WebServlet(name="UserController" ,urlPatterns = "/user")
public class UserController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// We can get it from the database.
        List userList = new ArrayList();
        userList.add(new User(1."Conan the Cow."."1, XXX City, XXX Province".new Date()));
        userList.add(new User(2."Conan the Great Conan 2."."Xx City, XX Province 2".new Date()));
        userList.add(new User(3."Conan the Great conan 3."."XXX City, XXX Province 3".new Date()));
        userList.add(new User(4."Conan the Great conan 4."."Xx City, XX Province 4".new Date()));
        userList.add(new User(5."Conan the Great Conan 5"."5, XXX City, XXX Province".new Date()));
        userList.add(new User(6."Conan the Great Conan 6.".6. "Xx City, XX Province".new Date()));

        String json = JSON.toJSONString(userList,   SerializerFeature.WriteDateUseDateFormat    );

		// Convert the format so that the front-end receives it
        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        out.write(json);
        out.flush();
        out.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp); }}Copy the code

Direct access to the http://127.0.0.1:8080/web/user is displayed when a json object, when we use port 80 to access front-end code, because the front will request the back-end through port 8080 json object, then need to access the backend at the same time 8080 ports and the front end of 80, Browsers do not allow this by default, and this is where cross-domain requests come in.

The solution

AddHeader (” access-Control-allow-Origin “,”*”); Allow simultaneous access, preferably by writing a filter. Put a CrossFilter on the back end.

CrossFilter code:

package com.neuedu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Keafmd
 *
 * @ClassName: CrossFilter
 * @Description:
 * @author: Conan the cow@date: whoever eats 2020-12-17 * /

// Filter all
@WebFilter(urlPatterns = "/*")
public class CrossFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.addHeader("Access-Control-Allow-Origin"."*");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy(a) {}}Copy the code

If it helps you, thank you for your support!

If you’re on the computer side, see the”Three even a key“Yeah, click on it.”




Come on!

Work together!

Keafmd