Recently, I used Springboot to develop the background interface, but after the interface is developed, I used JS to request the json data of the interface, and encountered annoying cross-domain problems. It took me a long time to find a solution. Here’s how to solve the problem.

First, write a Filter

Just put the following code into your SpringBoot project

package com.qcl; import org.springframework.stereotype.Component; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; /** * handle cross-domain issues * QCL: Component public class OriginFilter implements Filter {@override public void init(FilterConfig) filterConfig) throws ServletException { } @Override public voiddoFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin"."*");
        response.setHeader("Access-Control-Allow-Methods"."POST, GET, OPTIONS, DELETE,PUT");
        response.setHeader("Access-Control-Max-Age"."3600");
        response.setHeader("Access-Control-Allow-Headers"."x-requested-with");
        chain.doFilter(req, res);
    }

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

Two, use JS to do the request validation

As we need to request to https://localhost:8443/pv/2048/list for the following data, https://localhost:8443/pv/2048/list is my deployed on the server, due in 2020, you can also access

{
    "code": 100,
    "msg": "Success"."data": 3}Copy the code

The corresponding JS request code is as follows

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"</title> js+ Springboot resolves cross-domain requests </title> </head> <body> <script SRC ="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
    var baseUrl = "https://30paotui.com";

    $(document).ready(function() {$("button").click(function () {
            $.ajax({
                url: baseUrl + "/pv/2048/list", success: function (result) {
                    document.getElementById("p1").innerHTML = result; var str = JSON.stringify(result); Parse (STR); var obj = json.parse (STR); // Convert a JSON string to a JSON object console.log(STR); console.log(obj); console.log(obj.data); console.log(result.msg); console.log(result.code); }}); }); }); </script> <p id="p1"</button> </body> </ HTML >Copy the code

The request effect is as follows

If you have any questions about programming, please leave a message or send me a private message. I will answer them in time

Programming small stone, code farming, non – famous full stack developers. Share some of their own experience, learning experience, hope that later people less detour, less pit filling.