Хорошо, я посмотрел на это, и оказалось, что я скорее предпочел бы json в качестве ответа, чем текст / обычный текст. Поэтому я изменил свой весенний загрузочный контроллер, чтобы отправить обратно json.
Это позаботится о некоторых из них (идентификатор, мне не нужны необычные заголовки в моем запросе angular).
мой весенний загрузочный код выглядит так:
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
Теперь мой angular сервис выглядит так:
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
});
}
}
Теперь, прежде чем я продолжу работать почему я не получаю правильный ответ в свой компонентный файл. html, мне приходится работать с этой ошибкой:
в моем браузере angular, я получаю этот URL, который попадает на мой весенний сервер:
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, похоже, не выполняет то, чего я от нее ожидаю?
Тогда я перейду оттуда :)
Спасибо Крис