Spring Boot端点生成字符串响应并在Angular应用程序中显示该响应

问题描述 投票:0回答:2

我希望这不是转贴,因为我确实看过但找不到。

我有一个spring boot rest客户端,它调用rest端点。我正在使用angular来消耗该调用的结果,并将其传递给属于该组件的html文件。

我的Spring Boot代码看起来像这样:

package com.terida.teridaapp;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import java.util.*;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class TableauController {

    @RequestMapping(value = "/post", produces="text/plain")
    public String getTicketFromPost() {
        final String URL = "http://xxx.xxx.xxx.xxx/trusted";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept((Arrays.asList(MediaType.APPLICATION_JSON)));
        MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
        map.add("username", "admin");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        return restTemplate.exchange(URL,HttpMethod.POST,request,String.class).getBody();

    }
}

我有一个看起来像这样的角度服务:

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


@Injectable({
  providedIn: 'root'
})
export class GetTicketService {

  constructor(private http:HttpClient) { }

  ticket: any;
  url: any = "http://localhost:8100/api/post";

  public getTicket() {
    //return this.http.get("http://localhost:8100/api/post");
    //return this.http.get(this.url,{responseType: 'text'});
    //console.log(this.http.get("http://localhost:8100/api/post"));
    console.log("creating headers");
    const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    console.log("Making a url call to: " + this.url);
    console.log("the call: " + this.http.get(this.url,{ headers, responseType: 'text'}));
    return this.http.get(this.url,{ headers, responseType: 'text'});


  }
}

并且组件上的html是这样的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>Ticket Number: {{ticket}}</h1>>
    <h1>Message: {{message}}</h1>
</body>
</html>

我正在将一个对象传递回我的视图,并且我无法访问响应中的值。

有人想帮忙吗?

谢谢

angular spring-boot resttemplate
2个回答
0
投票

首先,您需要调用getTicket()方法,否则将不会发生任何事情。这次我将在构造函数上进行操作。

然后,当您调用http.get()时,该方法将返回您需要订阅的Observable。订阅后,您就可以执行所需的操作。

https://angular.io/guide/http

继续此操作,您的服务应为:

  ticket: any;
  url: any = "http://localhost:8080/api/post";


  constructor(private http:HttpClient) {
    this.getTicket();
    //You can do this on the onInit of a component as well. 
   }


  public getTicket() {

    const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    return this.http.get(this.url,  { headers, responseType: 'text' } )
      .subscribe( r =>
        { 
          this.ticket = r 
        });
  }

PS:遵循有角度的结构,我认为服务不应该具有HTML,它应该是一个Component,但也许我错了。


0
投票

好吧,我看了一眼,结果是,我宁愿将json作为响应而不是text / plain。因此,我修改了我的spring boot控制器以发送回json。

这可以解决其中的一些问题(id,我在我的角度请求中不需要花哨的标题)。

我的春季启动代码看起来像这样:

package com.terida.teridaapp;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import java.util.*;

@RestController
@RequestMapping("/api")

public class TableauController {

    @CrossOrigin(origins = "http://localhost:4200")
    //used this as a reference
    //https://howtodoinjava.com/spring-boot2/resttemplate/spring-restful-client-resttemplate-example/
    @RequestMapping(value = "/post", produces = MediaType.APPLICATION_JSON_VALUE, method= RequestMethod.POST)
    public String getTicketFromPost() {
        final String URL = "http://15.222.0.10/trusted";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept((Arrays.asList(MediaType.APPLICATION_JSON)));
        MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
        map.add("username", "admin");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,headers);
        return restTemplate.exchange(URL,HttpMethod.POST,request,String.class).getBody();

    }


}

我现在在邮递员中找回json:

Content-Type application/json

现在,我的角度服务看起来像这样:

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


@Injectable({
  providedIn: 'root'
})
export class GetTicketService {

  constructor(private http:HttpClient) { }

  ticket: any;
  url: any = "http://localhost:8100/api/post";

  public getTicket() {
    /*console.log("creating headers");
    const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    console.log("Making a url call to: " + this.url);
    console.log("the call: " + this.http.get(this.url,{ headers, responseType: 'text' as 'json'}));
    */

   const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
   return this.http.get(this.url,  { headers} )
     .subscribe( r =>
       { 
         this.ticket = r 
       });


  }
}

现在,在继续研究为什么我无法在我的component.html文件中获得正确的响应之前,我必须解决此错误:

在我的角度浏览器中,我得到的这个URL击中了我的spring服务器:

Access to XMLHttpRequest at 'http://localhost:8100/api/post' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Duration: 20 ms
HTTP/1.1 403 Forbidden
Transfer-Encoding: chunked
Keep-Alive: timeout=60
Connection: keep-alive
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Date: Thu, 23 Jan 2020 23:30:32 GMT

Invalid CORS request

所以,在我继续之前,也许您可​​以告诉我为什么我的@CrossOrigin批注似乎没有按照我的预期去做?

然后生病从那里继续:)

谢谢克里斯

© www.soinside.com 2019 - 2024. All rights reserved.