spring - 如何在 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();
}
解决方案
推荐阅读
- database - 具有单个 varchar 列与多个 varchar 列的复合索引
- php - mysqli_stmt::fetch(); 返回一个布尔值,但应该返回一个数组
- angular - ionic 3 angularx - flatpickr 弹出月历的所有日子都被禁用
- angular - Angular:ngx bootstrap 模式的单元测试用例覆盖率
- python - GridSearchCV 不适用于 Pipeline 的内存参数和并发性 (n_jobs > 1)
- cypress - 我们如何获取令牌并在响应中显示它
- firebase - 部署特定的 Firebase 云功能时部署了多少?
- excel - 计算数据透视表行的最高级别
- html - 悬停链接元素的一个元素
- javascript - 如何删除 JS 数组中的空尾随值和回车?