Приложение React не загружает пути к изображениям из MongoDB - PullRequest
0 голосов
/ 21 октября 2019

Я сохраняю массив потенциальных результатов поиска JSON в MongoDB, когда мое приложение React извлекает массив, оно не загружает изображение на основе значения JSON, которое является локальным путем на моем компьютере. Есть ли способ добавить require () к значению json с помощью клавиши «image»?

Результат в консоли: https://imgur.com/X6HMLkP

Как это выглядит на внешнем интерфейсе: https://imgur.com/ULb9Eqj

searchbank.json (что я отправляю в Монго)

[
  {
    "title": "Edd and Family",
    "description": "Some description",
    "image": "../src/Media/Modern/Ed.Silver088.jpeg"
  },
  {
    "title": "Sevek in San Francisco",
    "description": "Some description",
    "image": "../src/Media/Modern/Sevek267.jpeg"
  },
  {
    "title": "Sevek and Family",
    "description": "Some description",
    "image": "../src/Media/Modern/Sevek259.jpeg"
  },
  {
    "title": "Young Riva",
    "description": "Some description",
    "image": "../src/Media/Modern/Riva290.jpeg"
  },
  {
    "title": "Riva",
    "description": "Some description",
    "image": "../src/Media/Modern/Riva346.jpeg"
  }
]

server.js

const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const routes = express.Router();
const PORT = 4000;
let Bank = require("./searchbank.model.js");
var mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/tutorial", {
  useNewUrlParser: true
});
const connection = mongoose.connection;
connection.once("open", function(callback) {
  console.log("MongoDB database connection established successfully");
});
app.use(cors());
app.use(bodyParser.json());
routes.route("/").get(function(req, res) {
  Bank.find(function(err, results) {
    if (err) {
      console.log(err);
    } else {

      res.json(results);
    }
  });
});
app.use("/tutorial", routes);
app.listen(PORT, function() {
  console.log("Server is running on Port: " + PORT);
});

searchbank-model.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let Bank = new Schema(
  {
    title: { type: String },
    description: { Type: String },
    image: { Type: String }
  },
  { collection: "firstCollection" }
);
module.exports = mongoose.model("Bank", Bank);

App.js

const App = () => {
  const [results, setResults] = useState([]);
  const [searchBank, setSearchBank] = useState([]);
 const handleResultSelect = (e, { result }) => {
    setValue(result.title);
    setPerson(result);
    setOpen(true);
  };
  const handleSearchChange = (e, { value }) => {
    setIsLoading(true, value);
    setValue(value);

    setTimeout(() => {
      if (value.length < 1) {
        setIsLoading(false);
        setValue("");
        setResults([]);
      }
      console.log(searchBank);
      const re = new RegExp(_.escapeRegExp(value), "i");
      const isMatch = result => re.test(result.title);
      setIsLoading(false);
      setResults(_.filter(searchBank, isMatch));
    }, 300);
  };

  useEffect(() => {
    axios
      .get("http://localhost:4000/tutorial/")
      .then(response => {
        console.log("GET passsed.");
        setSearchBank(response.data);
      })
      .catch(function(error) {
        console.log(error);
      });
    setTimeout(() => {
      fetch("https://jsonplaceholder.typicode.com/posts")
        .then(response => response.json())
        .then(json => {
          setLoading(true);
          setTimeout(() => {
            setDone(true);
          }, 1000);
        });
    }, 2200);
    localStorage.setItem("dark", JSON.stringify(darkMode));
  }, [darkMode]);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...