scorpionsx
Hectopat
- Katılım
- 20 Mayıs 2022
- Mesajlar
- 96
Daha fazla
- Cinsiyet
- Kadın
Node.js ile social App yazıyorum. App'e resim yüklemeye çalışırken resim databasede, belirlediğim klasörde görünüyor ama sayfada görünmüyor. Yardımcı olur musunuz?
JavaScript:
Share.jsx
import { useContext, useRef, useState } from "react";
import "./share.css";
import { PermMedia, Label, Room, EmojiEmotions } from "@mui/icons-material";
import { AuthContext } from "../../context/AuthContext";
import axios from "axios";
import React from "react";
export default function Share() {
const { user } = useContext(AuthContext);
const PF = process.env.REACT_APP_PUBLIC_FOLDER;
const desc = useRef();
const [file, setFile] = useState(null);
const submitHandler = async (e) => {
e.preventDefault();
const newPost = {
userId: user._id,
desc: desc.current.value,
};
if (file) {
const data = new FormData();
const fileName = Date.now() + file.name;
data.append("file", file);
data.append("name", fileName);
newPost.img = fileName;
console.log(newPost);
try {
await axios.post("/upload", data);
} catch (error) {}
}
try {
await axios.post("/posts", newPost);
} catch (error) {}
};
return (
<div className="share">
<div className="shareWrapper">
<div className="shareTop">
<img
src={
user.profilePicture
? PF + user.profilePicture
: PF + "person/noAvatar.png"
}
alt=""
className="shareProfileImg"
/>
<input
placeholder={"What's in your mind " + user.username + "?"}
className="shareInput"
ref={desc}
/>
</div>
<hr className="shareHr" />
<form className="shareBottom" onSubmit={submitHandler}>
<div className="shareOptions">
<label htmlFor="file" className="shareOption">
<PermMedia htmlColor="tomato" className="shareIcon" />
<span className="shareOptionsText">Photo or Video</span>
<input
style={{ display: "none" }}
type="file"
id="file"
accept=".png,.jpeg,.jpg"
onChange={(e) => setFile(e.target.files[0])}
/>
</label>
<div className="shareOption">
<Label htmlColor="blue" className="shareIcon" />
<span className="shareOptionsText">Tag</span>
</div>
<div className="shareOption">
<Room htmlColor="green" className="shareIcon" />
<span className="shareOptionsText">Location</span>
</div>
<div className="shareOption">
<EmojiEmotions htmlColor="goldenrod" className="shareIcon" />
<span className="shareOptionsText">Feelings</span>
</div>
</div>
<button className="shareButton" type="submit">
Share
</button>
</form>
</div>
</div>
);
}
JavaScript:
index.js
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
const postRoute = require("./routes/posts");
const app = express();
const multer = require("multer");
const path = require("path");
const cors = require("cors");
dotenv.config();
mongoose.set("strictQuery", false);
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.log(err));
app.use("/images", express.static(path.join(__dirname, "public/images")));
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.use(cors());
app.use((req, res, next) => {
res.setHeader("Cross-Origin-Resource-Policy", "cross-origin"); // or 'cross-origin'
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
next();
});
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "public/images");
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
},
});
const upload = multer({ storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
try {
return res.status(200).json("File uploaded successfully!");
} catch (error) {
console.log(error);
}
});
app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
app.use("/api/posts", postRoute);
app.listen(8800, () => {
console.log("Backend server is running!");
});
Dosya Ekleri
Son düzenleyen: Moderatör: