【发布时间】:2022-01-21 15:36:59
【问题描述】:
问题
在渲染保存在后端的图像的路径时(使用 express),我在浏览器中看到损坏的图像。 我知道有类似的问题,但无法为我解决问题。
详情
我的server.ts 文件中有这个,在http://localhost:5000 中运行:
import express from 'express';
export const app = express();
require('dotenv').config();
import cookieParser from 'cookie-parser';
import path from 'path';
const pathToFile = path.resolve(__dirname, './public');
import cors from 'cors';
const corsOptions = {
credentials: true,
origin: 'http://localhost:3000',
}
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(pathToFile));
app.use(cors(corsOptions));
我在 http://localhost:3000 中运行的一个 react 应用程序组件中有这个:
{petToRender.petPicture &&
<img
src={`http://localhost:5000/${petToRender.petPicture.replace(/\\/g, "/").replace('public/','')}`}
/>}
我也试过没有.replace('public/',''),但它也不起作用。
更多参考和检查
petToRender.petPicture 的 mongoDB 上的数据看起来像屏幕截图所示并且被正确获取:
图片使用multer正确上传到./public/images:
在浏览器的控制台上 - 我得到:
GET http://localhost:5000/images/61b3441440535e9b69a74356.jpg 404 (Not Found)
当我输入图像直接链接时,控制台还会显示以下内容:
Refused to load the image 'data:image/png;base64,iVBORw0KGgoAAAA...' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback
【问题讨论】:
-
由于您使用 Typescript,我假设您必须先将其转换为 javascript,并且它可能放置在另一个文件夹中,例如 ./build,对吧?如果是这样,您传递给 express.static 的路径是否正确?尝试记录
__dirname变量以确保它指向正确的文件夹。或者试试console.log(pathToFile) -
谢谢!你是对的,它将 js 版本放在 ./dist 中。
标签: node.js typescript express content-security-policy transpiler