【问题标题】:Spring MVC & Angular - Reason: CORS header ‘Access-Control-Allow-Origin’ missingSpring MVC 和 Angular - 原因:缺少 CORS 标头“Access-Control-Allow-Origin”
【发布时间】:2021-02-11 03:01:23
【问题描述】:

当我尝试设置 Content-Type:application/json 时出现 CORS 错误原因:缺少 CORS 标头“Access-Control-Allow-Origin”

这是我在 Spring MVC 中的 Cors 覆盖:

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowCredentials(true).allowedMethods("GET", "POST", "PUT", "DELETE","OPTIONS").allowedHeaders("*").allowedOrigins("http://localhost:4200");
}

我的帖子 API:

@RequestMapping(value = "/seanPost", method = RequestMethod.POST)
public  String post(HttpServletRequest request, @RequestBody TrackFileStatusFindForm form ) {

我在 Angular 中的请求:

options = {
headers: new HttpHeaders()
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json')
};

this.http.post(this.APP_URL + '/seanPost', JSON.stringify(this.model), this.options)
.subscribe(
    data => {
        this.postId = data;
        console.log(this.postId);
    },
    error => {
    console.log('Error occured', error);
  }
) 

我的 Spring 项目在本地部署在 WebLogic 12c 上,如果有帮助,我将使用 https。

谢谢

【问题讨论】:

    标签: angular spring rest spring-mvc weblogic12c


    【解决方案1】:

    试试这个:

    private httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    

    【讨论】:

    • 没有仍然遇到相同的 cors 问题:跨域请求被阻止:同源策略不允许在 /seanPost 读取远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
    • 那么你的错误是服务器端的。帮不了你,我对spring不熟悉。
    • 好的。感谢您的帮助:)
    猜你喜欢
    • 2021-01-25
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2021-11-10
    • 2019-02-07
    • 2017-01-09
    • 2021-07-15
    相关资源
    最近更新 更多