前端跨域问题:Access-Control-Allow-Origin

1.背景

       最近在研究vue+springboot的前后端分离项目,遇到一个问题,从vue发送的请求后台能接收到并且返回,但是返回的消息前端接收不到,打开控制台看到报错信息:“......has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is......”,网上一查牵扯到跨域问题(CORS),本篇汇总三种方法

2.原因

       我vue前端端口为8080,springboot后台端口为8081,因此从8080端口与8081端口之间的请求属于跨域,当然,这也只是跨域的一种表现。

3.如何解决

       知道了原因,那么找到解决方法也就不难了,CORS官方面对这种情况也给出了解决方案,服务器可以通过HTTP 头字段(Access-Control-Allow-Origin)声明哪些源通过浏览器有权限访问哪些资源。

4.解决方法

       下面给出了三种解决方案,但是本质都是一样的,都是围绕HTTP 头字段(Access-Control-Allow-Origin)

     (1)代码如下

package com.zy.demo.controller;

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;

@Configuration
public class CorseConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);

    }
}

     (2)添加过滤器,代码如下


package com.zy.demo.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

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

@WebFilter(filterName = "CORSFilter", urlPatterns = {"/*"})
@Order(value = 1)
@Configuration
public class AccessControlAllowOriginFilter implements Filter {

    public void doFilter(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");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        chain.doFilter(req, response);
    }

    public void init(FilterConfig filterConfig) {

    }

    public void destroy() {

    }

}

注意:此类上的三个注解不能丢,或者在web.xml中配置filter.

    (3) 采用注解

@CrossOrigin(origins = "*")
package com.zy.demo.controller;


import com.zy.demo.entity.custom.UserLoginParam;
import com.zy.demo.entity.table.TUser;
import com.zy.demo.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private TUserService tUserService;

    @CrossOrigin(origins = "*")
    @RequestMapping("/login")
    public Object loginUser(UserLoginParam cUser){
        Map<String, Object> result = new HashMap<String, Object>();
        System.out.println(cUser);
        if("admin".equals(cUser.getCUsername())&&"123456".equals(cUser.getCPwd())){
            result.put("code",200);
            result.put("msg","登录成功");
            result.put("token","admin");
            return result;
        }

        result.put("code",500);
        result.put("msg","登录失败");
        return result;
    }

    @CrossOrigin(origins = "*")
    @RequestMapping("/userList")
    public List<TUser> userList(){
        return tUserService.userList();
    }
}

结语:三种方式介绍完毕,其实跨域问题值得探究的地方还有很多,大家下去可以自己研究一下。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

关阿炎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值