前端jquery请求后端springboot项目跨域解决方法及代码示例

前端jquery项目后端springboot项目跨域解决方法及代码示例— vue技术交流群(864583465) (此群满可加2群:111822407)

前端代码

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<button onclick="doReq()">请求button>
body>
<script src="./js/jquery.min.js">script>
<script>
    function doReq(){
        $.ajax({
            type: 'get',
            url: '你的接口地址', // 全链接
            contentType: 'application/json',
            dataType: 'json',
            success: function (res) {
                console.log(res)
            }
        })
    }
script>
html>

后端代码–配置类

package com.mashibing.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebConfigurer {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOriginPatterns("*")
                        .allowCredentials(true)
                        .allowedMethods("GET", "POST", "PUT", "DELETE");
            }
        };
    }
}

你的问答将是我们大家共同进步的关键!!!

你可能感兴趣的:(前端,jquery,spring,boot)