微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

CORS Angular和SpringBoot – 请求被阻止

我有一个问题,我似乎没弄明白.
我想发送一个来自我的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;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐