首页 > 解决方案 > 如何在 Angular 8 中调用 Rest API Post 方法。出现 CORS 错误

问题描述

我正在尝试在 Angular 8 中调用 Rest API post 方法。

  'Access-Control-Allow-Origin' :'*','Access-Control-Allow-Methods' :'POST, GET, PUT, OPTIONS, DELETE, PATCH','Access-Control-Max-Age' :'3600','Access-Control-Allow-Headers' :'Origin, X-Requested-With, Content-Type, Accept',
  'Content-Type': 'application/json',
  'username':'dexadmin','password':'dexcenter'}
  
  this.http.post('http://localhost:8080/DEXRESTAPI/queues/getMaxJob',{},{​​'headers':headers}).
  
  subscribe((data:any) => {​​

    console.log('Data', +data);

    console.log('Was my name');
  }​​);
}

Rest API is as below:

@RequestMapping(value = "/getMaxJob", method = RequestMethod.POST)
   public Integer getMaxJob() throws JmsException {
      
      try {
         return queueDelegate.getMaxJob();
      }
      catch (Exception cause) {
         logger.error("Error getting MaxJob" + cause.getMessage(), cause);
         throw new JmsException(cause.getLocalizedMessage());
      }
   }

我收到 401 未经授权的错误。我在控制台上遇到以下错误-CORS 策略已阻止从源“http://localhost:4200”访问“http://localhost:8080/DEXRESTAPI/queues/getMaxJob/”处的 XMLHttpRequest:响应预检请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我已经在 SecurityConfig.java 文件中设置

        http
                .httpBasic().disable()
                .csrf().disable()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/oauth/token").permitAll()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers(HttpMethod.GET).permitAll()
                .antMatchers(HttpMethod.POST).permitAll()
                .anyRequest().fullyAuthenticated();
    }

标签: springapirestangular8

解决方案


推荐阅读