GET request Angular+Spring not working. Why?

半城伤御伤魂 提交于 2020-03-05 00:21:31

问题


I'm trying to implement a simple GET request to send an Object of type SearchMessage from my Spring Boot server to my Angular client application. I run my server application and check if the relative JSON is correctly viewed on localhost:8080/greeting and it works. Here's what I see:

{
  "id": 1,
  "inputText": "Hello, World!",
  "targetSite": "Amazon",
  "searchLimit": 10,
  "numberOfProxies": 10,
  "details": false
}

I then run my client accessing to the component (http://localhost:4200/data) that is supposed to print in the log the content of that JSON, but instead I get in the console the following error. What am I doing wrong?

ERROR

Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "localhost:8080/greeting", ok: false, name: "HttpErrorResponse", message: "Http failure response for localhost:8080/greeting: 0 Unknown Error", error: error } core.js:6014:19

Spring application

Content of SearchMessage.java:

@Entity
public class SearchMessage {

    private long id;
    private String inputText;
    private String targetSite;
    private int searchLimit;
    private int numberOfProxies;
    private boolean details;

    // Getters, setters and constructors...
}

Content of GreetingController.java:

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public SearchMessage greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new SearchMessage(counter.incrementAndGet(), String.format(template, name), "Amazon", 10, 10, false);
    }
}

Raw data displayed at localhost:8080/greeting:

{"id":3,"inputText":"Hello, World!","targetSite":"Amazon","searchLimit":10,"numberOfProxies":10,"details":false}

Angular application

Content of my http.service.ts:

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class HttpService {

  constructor(private http: HttpClient) { }

  getGreeting() {
    return this.http.get('localhost:8080/greeting');
  }
}

Content of data.component.ts:

import {Component, OnInit} from '@angular/core';
import {HttpService} from '../http.service';

@Component({
  selector: 'app-data',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.scss']
})

export class DataComponent implements OnInit {
  greeting: Object;

  constructor(private _http: HttpService) {
  }

  ngOnInit() {
    this._http.getGreeting().subscribe(data => {
      this.greeting = data;
      console.log(this.greeting);
    });
  }
}

Content of search-message.ts:

export class SearchMessage {

  constructor(
    public id: number,
    public inputText: string,
    public targetSite: string,
    public searchLimit: number,
    public numberOfProxies: number,
    public details: boolean
  ) { }
}

回答1:


To allow CORS Origin support to your backend application you have to create a Configuration class which add Cors origin and allow to your frontend application to be able to call APIs exposed by your Spring Boot application:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("http://localhost:4200");
    }
}

You can find an example here.


I'm not sure that the problem is related to CORS, but for sure you have to add it.




回答2:


In the controller class add:

@CrossOrigin(origins = "http://localhost:4200")

above the @RestController annotation to make your spring boot app and angular app connect with each other. This is a sample controller class hope it helps.

     @CrossOrigin(origins = "http://localhost:4200")
     @RestController

     public class StudentsController{

    @Autowired
    StudentRepo repo;

    //insert
   @PostMapping("/students")
   public Students insert(@Valid @RequestBody Students students){
    return repo.save(students);
    }
   //list of students   
   @GetMapping("/students")
   public List<Students> index(){
   return repo.findAll();
   }}


来源:https://stackoverflow.com/questions/60024146/get-request-angularspring-not-working-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!