GET请求Angular + Spring无法正常工作。为什么?

时间:2020-02-02 07:45:19

标签: angular spring-boot http get

我正在尝试实现一个简单的 GET请求,以将类型为SearchMessage的对象从我的 Spring Boot 服务器发送到我的 Angular < / strong>客户端应用程序。我运行服务器应用程序,并检查在localhost:8080/greeting上是否正确查看了相对JSON,并且它可以工作。 这是我看到的:

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

然后,我运行我的客户端,访问应该在日志中打印该JSON内容的组件(http://localhost:4200/data),但是相反,我在控制台中遇到以下错误。我在做什么错了?

错误

对象{标头:{…},状态:0,statusText:“未知错误”, url:“ localhost:8080 / greeting”,确定:false,名称:“ HttpErrorResponse”, 消息:“对本地主机的HTTP故障响应:8080 /问候:0未知 错误”,错误:错误} core.js:6014:19

Spring应用程序

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...
}

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);
    }
}

原始数据显示在localhost:8080/greeting

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

角度应用

我的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');
  }
}

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);
    });
  }
}

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
  ) { }
}

2 个答案:

答案 0 :(得分:0)

在控制器类中添加:

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

@RestController注释上方,以使您的Spring Boot应用程序和angular应用程序彼此连接。 这是一个希望对您有所帮助的示例控制器类。

     @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();
   }}

答案 1 :(得分:0)

要为后端应用程序提供CORS Origin支持,您必须创建一个Configuration类,该类添加Cors起源并允许您的前端应用程序调用Spring Boot应用程序公开的API:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

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

您可以找到示例here


我不确定问题是否与CORS有关,但是可以肯定的是,您必须添加它。