【发布时间】:2020-03-15 09:38:14
【问题描述】:
所以我试图从我的 Spring Boot 后端发出一个“GET”请求,我收到了响应,但图片是作为错误参数出现的。我可以使用错误参数并使用网站上的图片,但即使状态为 200,我仍然会得到错误。
后端代码:
@CrossOrigin(origins="http://localhost:4200")
@GetMapping(
path = "/images/path-variable/{name}"
)
static public ResponseEntity<String> getImageWithMediaType(@PathVariable String name) throws IOException, Exception {
System.out.println("/images/" + name + ".jpg");
File tempFile = new File("/home/ninhow/Desktop/antons-skafferi-front-back/backend/src/main/resources/images/restaurant_1280x853.jpg");
return ResponseEntity.ok(CodecBase64.encode(tempFile, true));
}
在 Angular 中,我向我的服务发出请求:
@Injectable({
providedIn: 'root'
})
export class GetImageService {
constructor(private http: HttpClient) { }
getImage(){
return this.http.get<any>("http://localhost:8080/images/path-variable/restaurant_1280x853");
}
}
我用来接收响应并使用它的组件函数:
export class HeaderComponent implements OnInit {
image: any;
constructor(private service: GetImageService, private sanitizer: DomSanitizer) { }
ngOnInit() {
this.getHeaderImage();
}
getHeaderImage(){
this.service.getImage().subscribe(data => {
console.log(data);
this.image = "data:image/jpeg;base64" + data;
}, error=>{
var response = "data:image/jpeg;base64," + (error as any).error.text
console.log(error);
this.image = this.sanitizer.bypassSecurityTrustResourceUrl(response);
});
}
}
基本上我想做的是从我的后端发送一张图片,这样我就可以在我的前端使用而不会出错:
组件的html文件:
<p>header works!</p>
<div>
<img [src]="image" alt="">
</div>
浏览器控制台错误:
https://i.stack.imgur.com/gumCw.png
使用重载编辑我的 getImage 函数后,函数如下所示:
getImage(){
return this.http.get("http://localhost:8080/images/path-
variable/restaurant_1280x853", {
responseType: "text"
});
}
【问题讨论】:
-
阅读错误信息。它告诉我们出了什么问题。 HttpClient 尝试将您的 base64 文本解析为 JSON,因为您没有使用正确的 get() 重载。 angular.io/api/common/http/HttpClient#get
-
我应该在我的服务的 getImage 函数上添加选项吗?
-
是的。您想使用返回 Observable
的重载。在文档中找到它,并传递选择此重载所需的选项。 -
所以我解决了错误,但我得到了新的错误,我得到了 base64 的响应......唯一的问题是我得到“net::ERR_CONNECTION_RESET 431(请求标头字段太大”
-
对于每一个询问错误的问题,您都需要提供相关代码、准确完整的错误信息/堆栈跟踪,并说明该错误出现的时间、地点和方式。
标签: angular spring-boot frontend backend