【发布时间】:2021-08-14 05:33:40
【问题描述】:
问题描述
我在从 postgreSQL 数据库获取多个图像并将其显示在我的前端时遇到问题。图像作为二进制数据存储在 postgreSQL 中。如果我运行我的快速代码,我会以 json 格式将图像数据作为缓冲区返回。 当我运行代码时,我收到一个 200 状态码,但 observable 最终执行了 handleError 函数。 在这里你可以看到我的控制台 --> console
我的目标
我想从一个房子中获取多张图像以显示在我的前端模式页面上,这些图像存储在数据库中的一个单独的表中。通过我的 postgreSQL 数据库中的这个查询("select * from housee.houses_images where straatnaam = $1 AND straatnr = $2 AND postcode = $3",) ,我可以获得正确的图像。获得所有图像后,我想在 ion-img 标签中显示它们(来自 ionic 框架)
代码信息
所以我使用 postgresSQL 数据库,使用 express.js 库和 Angular 中的前端在 javascript 中使用后端。
这是我在 postgreSQL 中的表--> table postgreSQL
在我的 backend index.js 文件中有这段代码
app.get(
"/getMarkerPhotos/:straatnaam/:straatnr/:postcode",
function (req, res) {
client.query(
"select * from housee.houses_images where straatnaam = $1 AND straatnr = $2 AND postcode = $3",
[req.params.straatnaam, req.params.straatnr, req.params.postcode],
function (err, data) {
if (err != null) {
res.sendStatus(500);
} else {
res.sendStatus(200);
}
}
);
}
);
后端的调用正在工作,因为如果我在邮递员中运行它,它会以 JSON 格式返回我的数据 --> postman
在前端,在我的 api.service.ts 文件中,我创建了这个函数
getMarkerPhotos(straatnaam: any, straatnr: any, postcode: any): Observable<any> {
var result = this.http.get(this.url + '/getMarkerPhotos/' + straatnaam + '/' + straatnr + '/' + postcode)
.pipe(
catchError(this.handleError)
);
console.log(result)
return result
}
<--other code-->
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log(error.error.message)
} else {
console.log(error.status)
}
return throwError(
console.log('Something is wrong!'));
};
在我想要显示来自数据库的图像的模态页面 (maker-modal.components.ts) 上,我有此代码
ngOnInit() {
this.getMarkerPhotos();
}
getMarkerPhotos() {
this.api.getMarkerPhotos(this.straatnaam, this.straatnr, this.postcode).subscribe(
data => {
console.log(data)
//this.photos.push(data)
//console.log(this.photos)
},
error => {
console.log("Subscribe error: " + error)
}
);
}
我希望有人可以帮助我解决这个问题。 提前致谢!
【问题讨论】:
-
你认为你和这篇文章有同样的问题吗? stackoverflow.com/questions/53605619/… “默认情况下,Angular HttpClient 会尝试将 HTTP 响应的主体解析为 JSON”。在您的后端 index.js 中尝试使用
res.status(500).send({});res.status(200).send({}); -
我试图按照他们在该帖子中所做的解决方案。但是当我在 url 之后执行 `{responseType: 'text'}` 时,我会在文本中恢复正常。我来自后端调用的数据不存在。另外,如果我添加您的
res.status(200).send({});,我的后端崩溃并给我这个错误_http_outgoing.js:558 throw new ERR_HTTP_HEADERS_SENT('set') Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client -
你还在用
res.sendStatus(...)吗?错误说Cannot set headers after they are sent to the client所以你不能同时使用,你必须使用res.status(...).send({})或res.sendStatus(...):if (err != null) { res.status(500).send({}); } else { res.status(200).send({}); } -
哦,是的,它正在工作。事实上,我也发现你不能同时使用两者。所以我只使用
res.send({data}),现在我可以在前端获取所有图像!感谢您的帮助:)
标签: javascript angular postgresql express