ajax/axios调用后端接口跨域问题 has been blocked by CORS policy: No Access-Control-Allow-Origin

https://blog.csdn.net/lovePaul77/article/details/85681404

ajax+springboot解决跨域问题,以下报的错误就是html跨域的问题

Access to XMLHttpRequest at 'http://localhost:8080/user/login1' from origin 'http://localhost:59033' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

springboot解决跨域的问题的两种方法

前端测试代码:



 

   
   

 


   

       

用户名:


       

密 码:


       

 


   





 

 

第一种:写一个class,配置的class

package com.example.demo;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
 
 
/**
 * Author:Yangjingcheng
 * Date:2018/
 */
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }
 
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 配置所有请求
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}
第二种,在你要访问的Controller的方法上面加上注解

@CrossOrigin


例子:

package com.example.demo;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
 
@Controller
public class TestController {
 
 
    @CrossOrigin
    @RequestMapping("/user/login1")
    @ResponseBody
    public List userLogin(User user) {
        System.out.println(user);
        ArrayList users = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            users.add(user);
        }
        return users;
    }
}
这样的话就会解决前端接收不到返回值得情况了
 

你可能感兴趣的:(VueJs,JS)