CORS Angular和SpringBoot - 请求被阻止

时间:2018-04-03 00:33:05

标签: spring angular spring-boot

我有一个问题,我似乎没弄明白。 我想从我的

发送一个http请求

Angular客户:

import Data.List.NonEmpty as NE (NonEmpty(..), (<|), head, tail)

splitStringOnDelimeter :: String -> Char -> NonEmpty String
splitStringOnDelimeter string delimiter = foldr f (pure "") string
  where f h split = if h == delimiter 
                      then ("" <| split) 
                      else (h : NE.head split) :| NE.tail split

到我使用CORS注释的SpringBoot后端:

const url = 'http://localhost:8080/api';
console.log(this.http.get(url).subscribe(data => this.greeting = data));

但是我收到一个错误,它被阻止并重定向我一直登录。

@CrossOrigin(origins = "http://localhost:4200/", maxAge = 3600)
    @RequestMapping("/api/")
    public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
    }

有没有办法改变它?

我感谢任何有关此事的暗示或帮助。我想了解为什么会出现这个问题。

4 个答案:

答案 0 :(得分:5)

您的RequestMapping中有错误,因为您使用了@RequestMapping("/api/"),这将被评估为http://your_url/api//。您的控制器中不存在此类映射,因此它会为您提供CORS Origin错误。

只需从/移除尾随@RequestMapping("/api/"),即可@RequestMapping("/api")

您的课程应如下所示,

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class DemoController {

    @RequestMapping(value = "/api", method = RequestMethod.GET)
    public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
    }
}

答案 1 :(得分:1)

这是服务器端的问题。您所要做的就是在服务器端执行一个组件,它将解决问题。或参考here

请遵循以下代码:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
            try {
                chain.doFilter(req, res);
            } catch(Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Pre-flight");
            response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "authorization, content-type," +
                    "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
            response.setStatus(HttpServletResponse.SC_OK);
        }

    }
    }

答案 2 :(得分:0)

由于您已选择为自己的应用添加注释,因此必须单独为每种方法提供@CrossOrigin注释。这意味着您还必须:

@CrossOrigin(origins = "http://localhost:4200/", maxAge = 3600)
    @RequestMapping("/login/")
    public Map<String,Object> login() {
     /* ... */
    }

参考:https://spring.io/guides/gs/rest-service-cors/#_enabling_cors

答案 3 :(得分:0)

不是使用@Crossorigin注释每个方法,而是可以使用filter中的web.xml,如下所述

将以下过滤器添加到web.xml文件。

 <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

下面给出了所述罐子的依赖性。

<dependency>
            <groupId>com.thetransactioncompany</groupId>
            <artifactId>cors-filter</artifactId>
            <version>2.5</version>
        </dependency>

多数民众赞成 - 完成。