【问题标题】:React/node => image display not allowed to load local ressourceReact/node => 图像显示不允许加载本地资源
【发布时间】:2022-02-08 21:24:54
【问题描述】:

我正在进行一个 react/node 网站项目。非常简单的网站,带有杂物。 我的 crud 工作,但我的图片没有出现(它们上传到文件夹 public/uploads/news/ 并且它们的路径保存在 mongoDb 中)对于我的新闻,我可以看到标题、消息、日期,但图片已损坏,我只有alt。 当我去控制台并继续元素时,补丁可以“c:/users/............ /public/uploads/news/nameofmypicture.jpg”。 我刚刚收到一条错误消息“不允许加载本地资源”

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { dateParser, isEmpty } from "../../../general/utils/Utils";
import { updateNews } from "../../../../store/actions/news.actions";
import DeleteCard from "./DeleteCard";
import Loader from "../../../general/utils/Loading";

const Card = ({ news }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [isUpdated, setIsUpdated] = useState(false);
    const [textUpdate, setTextUpdate] = useState(null);
    const newsData = useSelector((state) => state.newsReducer);
    const dispatch = useDispatch();

    const updateItem = () => {
        if (textUpdate) {
            dispatch(updateNews(news._id, textUpdate));
        }
        setIsUpdated(false);
    };

    useEffect(() => {
        !isEmpty(newsData[0]) && setIsLoading(false);
    }, [newsData]);

    return (
        <li className="card-container" key={news._id}>
            {isLoading ? (
                <Loader />
            ) : (
                <>
                    <div className="card-right">
                        <div className="card-header">
                        {isUpdated === false && <h3>{news.title}</h3>}
                        {isUpdated && (
                            <div className="update-title">
                                <textarea
                                    defaultValue={news.title}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />
                            </div>
                        )}
                            <span>{dateParser(news.createdAt)}</span>
                        </div>
                        {isUpdated === false && <p>{news.message}</p>}
                        {isUpdated && (
                            <div className="update-post">
                                <textarea
                                    defaultValue={news.message}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />
                                <div className="button-container">
                                    <button className="btn btn-success" onClick={updateItem}>
                                        Valider modification
                                    </button>
                                </div>
                            </div>
                        )}
                        {news.picture && (
                            <img src={news.picture} alt="card-pic" className="card-pic" />
                        )}
                        {news.video && (
                            <iframe
                                width="500"
                                height="300"
                                src={news.video}
                                frameBorder="0"
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                allowFullScreen
                                title={news._id}
                            ></iframe>
                        )}
                        <div className="button-container">
                            <button className="btn btn-primary" onClick={() => setIsUpdated(!isUpdated)}>Edit</button>
                            <DeleteCard id={news._id} />
                        </div>
                    </div>
                </>
            )}
        </li>
    );
};

export default Card;

如果有人想要完整的代码 https://github.com/macath/AJC-modelism 如果您有更多问题,请问我。我从4天开始就遇到这个问题,我真的不明白为什么它不起作用。 我指定这个项目将上线,所以我需要在服务器上而不是本地的有效解决方案

Ps : 对不起我的英语我是法国人

【问题讨论】:

  • 图像不能有文件系统的绝对路径...它们需要由 Web 服务器提供服务,并且需要有 URL 来识别和加载它们

标签: javascript node.js reactjs


【解决方案1】:

感谢@Rolland Costomarob 和@Siddharth Seth 我认为问题在于,我使用 multer 上传我的图片,我认为我没有正确使用它。

const router = require('express').Router();
const newsController = require('../controllers/news.controller');

const multer = require('multer');
const imageStorage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './client/public/uploads/')
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, 'file-' + uniqueSuffix + '.jpg')
    }
});
const upload = multer({
    limits: {
        fileSize: 10000000
    },
    fileFilter: (req, file, cb) => {
        if (file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg') {
          cb(null, true);
        }
        else {
          cb(new multer.MulterError('mauvais format de document'));
        }
      },
    storage: imageStorage
});

router.get('/', newsController.readNews);
router.post('/', upload.single('file'), newsController.createNews);
router.put('/:id', newsController.updateNews);
router.delete('/:id', newsController.deleteNews);

module.exports = router;

如果你有解决办法,你就救了我的命

【讨论】:

    【解决方案2】:
    【解决方案3】:

    问题解决了。在我的 news.controller 中,我替换了

    picture: req.file.path
    

    通过

    picture: req.file.filename
    

    在我的 card.js 我替换

    img src={news.picture}
    

    通过

    <img src={`${window.location.origin}/uploads/${news.picture}`}
    

    感谢您的帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 2016-11-04
      • 2019-05-24
      • 2014-12-10
      • 1970-01-01
      相关资源
      最近更新 更多