簡體   English   中英

CORS Angular和SpringBoot - 請求被阻止

[英]CORS Angular and SpringBoot - request blocked

我有一個問題,我似乎沒弄明白。 我想發送一個來自我的http請求

Angular客戶:

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

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

@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;
    }

但我收到一個錯誤,它被阻止並重定向我一直登錄。

Failed to load http://localhost:8080/api: Redirect from 'http://localhost:8080/api' to 'http://localhost:8080/login' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. 

有辦法改變嗎?

我很欣賞任何暗示或幫助。 我想了解為什么會出現這個問題。

您在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;
    }
}

這是服務器端的問題。 您所要做的就是在服務器端執行一個組件,它將解決問題。 或者在這里參考

請遵循以下代碼:

@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);
        }

    }
    }

由於您已選擇為應用程序添加注釋,因此必須單獨為每個方法提供@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

您可以在web.xml使用filter ,而不是使用@Crossorigin注釋每個方法,如下所述

將以下過濾器添加到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>

多數民眾贊成在這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM