我的應用程式有奇怪的問題。我的應用程式是這樣構建的 ts(angular) -> java(spring)。我在 angular 中隨意添加了一些 Gets 到 java,也洗掉了請求,但是當我要添加 post 請求時,我遇到了問題。我的應用程式正在使用 httpbasic 身份驗證。所以讓我向您展示一些代碼:這是來自我的資料服務的代碼
getCurrentCars(id:number){
const headers = new HttpHeaders({ 'Content-Type':'application/json',
'Authorization': 'Basic ' btoa(sessionStorage.getItem('username') ':' sessionStorage.getItem('password')) });
return this.http.get("http://localhost:8080/api/cars/getcurrentcars/" id.toString(),{headers});
}
postNewRepair(name:string, description:string, date:string, idCar:number){
const headers = new HttpHeaders({ 'Content-Type':'application/json',
'Authorization': 'Basic ' btoa(sessionStorage.getItem('username') ':' sessionStorage.getItem('password')) });
let newrepair:Repair= {name: name, date:date, description:description, idCar:idCar}
this.http.post("localhost:8080/api/repairs/postRepair",newrepair,{headers}).subscribe(resp => console.log(resp));
}
獲得作品,發布不想作業,但來自郵遞員 POST WORKS FINE
ofc 我做了一些 Cors 策略禁用,這里有一些例子:
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/api/repairs")
public class ControllerRepair {
@RequestMapping(method = RequestMethod.POST, value = "/postRepair")
public void postRepair(@RequestParam String name, @RequestParam String date, @RequestParam String description, @RequestParam Long idCar){
LocalDate date1 = LocalDate.parse(date);
System.out.println("aaa");
iRepairService.postRepair(name, date1, description, idCar);
}
}
這里來自 http 配置
http
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/repairshops/**").hasAuthority("REPAIR_SHOP")
.antMatchers("/api/clients/**").hasAnyAuthority("CLIENT","REPAIR_SHOP")
.antMatchers("/login/**").fullyAuthenticated()
.anyRequest()
.authenticated()
.and()
.httpBasic();
而且我也嘗試了這個 cors 配置類,我在堆疊的某個地方找到了它,但它根本不起作用,并且還使我的其他獲取和洗掉請求不起作用
Access to XMLHttpRequest at 'localhost:8080/api/repairs/postRepair' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
也許我沒有在我的 http 帖子中使用一些標題來使它作業?
uj5u.com熱心網友回復:
我看到您在帖子請求的網址中遺漏了“http”?讓我們把它像之前的 GET 一樣,然后再試一次。
this.http.post("http://localhost:8080/api/repairs/postRepair", newrepair, { headers })
.subscribe(resp => console.log(resp));
uj5u.com熱心網友回復:
使用當前設定 ( http.cors()),您將使用 spring ( https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html )提供的默認 cors 配置。您可以使用指南 ( https://spring.io/blog/2015/06/08/cors-support-in-spring-framework ) 為您的用例配置它。
如果您只想嘗試一下,可以將其用作臨時解決方案:
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/374239.html
