创建反应应用程序并通过 php 文件动态加载图像
create-react-app and loading image dynamically via php file
我正在将一个 react/php 项目(在 apache 上是 运行)迁移到 create-react-app 等 Express。js/live 重新加载等(用于开发)。
在此项目中,有用户上传的图像,它们通过 php 文件保存在文档根目录之外,该文件接受要加载的文件名作为查询字符串。
file.php?image=file_name.png
其相对的react组件是
const Img = (props) => {
const findFile = () => {
// base64
if(props.file && props.file.startsWith('data:image/')){
return props.file;
}
return "file.php?name=" + props.file + "&type=" + props.type;
};
return (
<img src={findFile()} alt={props.alt || props.file}/>
);
};
迁移到create-react-app后,我在package.json
中添加了代理
"proxy":"http://localhost"
但通过这种方式,只有当用户在仪表板页面时才会加载图像。在其他页面中,图像不起作用,因为更改了 file.php.
的路径
在仪表板中 (http:/localhost/auth)
127.0.0.1 - - [10/Oct/2017:23:59:12 +0200] "GET /file.php?name=avatar4.png&type=avatarDefaultDir HTTP/1.1" 200 12295
在其他页面中(例如:http://localhost/auth/profile)
127.0.0.1 - - [10/Oct/2017:23:59:17 +0200] "GET /auth/file.php?name=avatar4.png&type=avatarDefaultDir HTTP/1.1" 200 27
我该如何解决这个问题?
您需要使用 file.php 文件的正确路径并使用 file.php
的绝对路径
而不是
return "file.php?name=" + props.file + "&type=" + props.type;
使用
return "/file.php?name=" + props.file + "&type=" + props.type;
这是假设 file.php 在您项目的根目录中
我正在将一个 react/php 项目(在 apache 上是 运行)迁移到 create-react-app 等 Express。js/live 重新加载等(用于开发)。
在此项目中,有用户上传的图像,它们通过 php 文件保存在文档根目录之外,该文件接受要加载的文件名作为查询字符串。
file.php?image=file_name.png
其相对的react组件是
const Img = (props) => {
const findFile = () => {
// base64
if(props.file && props.file.startsWith('data:image/')){
return props.file;
}
return "file.php?name=" + props.file + "&type=" + props.type;
};
return (
<img src={findFile()} alt={props.alt || props.file}/>
);
};
迁移到create-react-app后,我在package.json
中添加了代理"proxy":"http://localhost"
但通过这种方式,只有当用户在仪表板页面时才会加载图像。在其他页面中,图像不起作用,因为更改了 file.php.
的路径在仪表板中 (http:/localhost/auth)
127.0.0.1 - - [10/Oct/2017:23:59:12 +0200] "GET /file.php?name=avatar4.png&type=avatarDefaultDir HTTP/1.1" 200 12295
在其他页面中(例如:http://localhost/auth/profile)
127.0.0.1 - - [10/Oct/2017:23:59:17 +0200] "GET /auth/file.php?name=avatar4.png&type=avatarDefaultDir HTTP/1.1" 200 27
我该如何解决这个问题?
您需要使用 file.php 文件的正确路径并使用 file.php
的绝对路径而不是
return "file.php?name=" + props.file + "&type=" + props.type;
使用
return "/file.php?name=" + props.file + "&type=" + props.type;
这是假设 file.php 在您项目的根目录中