在将spring boot应用程序与我的angular应用程序连接时遇到问题。我想从角度执行get请求。为此,我通过将控制器注释为@CrossOrigin在Spring Boot应用程序中进行了更改。 到目前为止,我可以从角度访问tomcat网址,因为spring boot中的日志可以正确发布。但是,我无法在我的角度应用程序中获取任何响应。
I believe it is related to type. For simplest type-String, I had tried but no help. I am getting the below error:
```XHR failed loading: GET "http://localhost:8080/home".```
Here is my spring boot:
```
@CrossOrigin
@RestController
public class HomeController {
private CoronavirusDataService coronavirusDataService;
@Autowired
public HomeController(CoronavirusDataService coronavirusDataService)
{
this.coronavirusDataService=coronavirusDataService;
}
@GetMapping("/home")
public String home() throws IOException, InterruptedException, JSONException {
String abc="Ria";
List<LocationStats> locationStatsList= coronavirusDataService.fetchVirusData();
//locationStatsList.stream().forEach(System.out:: println);
//var myObj = JSON.parse('{"p": 5}');
//return locationStatsList.toString();
return abc;
}
}```
Here is my angular:
```import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {CoronaData} from '../model/corona-data';
@Component({
selector: 'app-corona-module',
templateUrl: './corona-module.component.html',
styleUrls: ['./corona-module.component.css']
})
export class CoronaModuleComponent implements OnInit {
coronaCount: CoronaData[] = [];
coronaC: string;
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.getAllCases();
console.log(this.coronaCount);
}
public getAllCases(){
const url = 'http://localhost:8080/home';
this.http.get<string>(url).subscribe(
res => {
this.coronaC = res;
console.log(this.coronaC);
},
error => {
alert('An error has occured');
console.log(this.coronaC);
}
);
}
}```
I am quite struggling with basic, any help in this regard will be appreciated.
Thank you!
答案 0 :(得分:0)
通过以下更改修改我的角度函数:
public getAllCases(){
const url = 'http://localhost:8080/home';
this.http.get(url, {responseType: 'text' }).subscribe(
res => {
this.coronaC = res;
console.log(this.coronaC);
},
error => {
alert('An error has occured');
console.log(this.coronaC);
}
);
}```