Я пытаюсь отправить изображение из Express в React, действительно, я сначала загрузил изображение из React в Express, используя Multer, я вижу, что изображение сохраняется на правильном локальном компьютере, поэтому я отправляю ответ для внешнего интерфейса, используя локальный путь (/ public / img / users /), даже используя app.use (express .stati c (__ dirname + "publi c")), все равно не работает;
серверная часть
server.js
``const app = require("./app");
const port = 5013;
app.listen(port, () => {
return console.log(`the server is connected in ${port}`);
});``
app.js
``const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const userRoutes = require("./routes/userRoutes");
var cors = require("cors");
const app = express();
app.use(cors());
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(express.static(__dirname + "public"));
app.use("/", userRoutes);
module.exports = app;``
``
useController
const multer = require("multer");
const sharp = require("sharp");
const multerStorege = multer.memoryStorage();
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("not a image Please upload only images.", false);
}
};
const upload = multer({
storage: multerStorege,
fileFilter: multerFilter,
});
exports.uploadUserImage = upload.single("image");
exports.resizeUserImage = (req, res, next) => {
req.file.filename = `user-${Date.now()}.jpeg`;
if (!req.file) return next();
sharp(req.file.buffer)
.resize(500, 500)
.toFormat("jpeg")
.jpeg({ quality: 90 })
.toFile(`public/img/users/${req.file.filename}`);
next();
};
``
exports.getImage = (req, res) => {res.status (200). json ({image_path: /public/img/users/${req.file.filename}
, image_name: req.file. название, }); };
``front end
app.js
import React from "react";
// import "./App.css";
import DefaultTemplate from "./DefaultTemplate";
function App() {
return <DefaultTemplate />;
}
export default App;
DefaultTemplate
import React, { useState } from "react";
import axios from "axios";
const DefaultTemplate = () => {
const [image, setImage] = useState("");
const [uploadedFile, setUploadedFile] = useState({});
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("image", image);
try {
const res = await axios.post("/uploadImg", formData, {
headers: {
"Content-type": "multipart/form-data",
},
});
const { image_path, image_name } = res.data;
setUploadedFile({ image_path, image_name });
} catch (error) {
if (error.response.status === 500) {
console.log("there is a problem");
}
}
};
const handleChange = (e) => {
setImage(e.target.files[0]);
};
if (uploadedFile.image_path) {
console.log("/" + uploadedFile.image_path);
}
return (
<>
<form onSubmit={handleSubmit}>
<input type="file" onChange={handleChange} />
<div name=""></div>
<input type="submit" />
</form>
<img src={uploadedFile.image_path} />
</>
);
};
export default DefaultTemplate;
``