GET请求Angular + Spring无法正常工作.为什么? [英] GET request Angular+Spring not working. Why?

查看:100
本文介绍了GET请求Angular + Spring无法正常工作.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

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

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?

错误

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

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应用程序

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

推荐答案

在控制器类中添加:

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

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

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

这篇关于GET请求Angular + Spring无法正常工作.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆