Ola, estou adornando o curso, porém fiz testes com angular 2 fazendo POST e GET para uma URL externa exemplo de uma API em java que montei para testar a aplicação "http://192.168.55.200:8080/foto/nova"; então tive vários erros, e não consegui resolver nenhum, gostaria de ajuda sobre como usar o Angular 2 fazendo CRUD para URL externas; Obrigado.
Aqui está o contoller da API pra teste
@Controller @RequestMapping("/foto/") public class FotoConctroller {
private List fotoList = new ArrayList<>();
@RequestMapping(value = "nova", consumes = "application/json; charset=UTF-8", produces = "application/json; charset=UTF-8") public ResponseEntity novo(@RequestBody Foto foto) { System.out.println(foto); fotoList.add(foto);
return new ResponseEntity<>(foto, HttpStatus.CREATED); }
@RequestMapping(value = "lista", produces = "application/json; charset=UTF-8") public ResponseEntity> getLista() {
return new ResponseEntity<>(fotoList, HttpStatus.OK); } }
JS do Angular
cadastrar(event) { event.preventDefault();
console.log(this.foto) let headers = new Headers(); headers.append("Content-Type", "application/json");
let body = JSON.stringify(this.foto); console.log(body); this.http .post("http://192.168.55.200:8080/foto/nova", body, { headers: headers }) .subscribe(() => { this.foto = new FotoComponent(); console.log("Foto salva com sucesso!"); }, error => console.log(error));
}
Os erros
zone.js:1382 OPTIONS http://192.168.55.200:8080/foto/nova 415 (Unsupported Media Type)
XMLHttpRequest cannot load http://192.168.55.200:8080/foto/nova. Response for preflight has invalid HTTP status code 415
Response {body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers, …} headers : Headers {headersMap: Map(0)} ok : false status : 0 statusText : "" type : 3 url : null body : ProgressEvent bubbles : false cancelBubble : false cancelable : false composed : false currentTarget : XMLHttpRequest {zone_symbolxhrSync: false, zone_symboleventTasks: Array(1), zone_symbolxhrTask: ZoneTask, readyState: 4, timeout: 0, …} defaultPrevented : false eventPhase : 0 isTrusted : true lengthComputable : false loaded : 0 path : [] returnValue : true srcElement : XMLHttpRequest {zone_symbolxhrSync: false, zone_symboleventTasks: Array(1), zone_symbolxhrTask: ZoneTask, readyState: 4, timeout: 0, …} target : XMLHttpRequest {zone_symbolxhrSync: false, zone_symboleventTasks: Array(1), zone_symbolxhrTask: ZoneTask, readyState: 4, timeout: 0, …} timeStamp : 100747.095 total : 0 type : "error" _proto : ProgressEvent __proto : Body