Gabi Moldovan
Gabi Moldovan

Reputation: 17

How to send data from react js to a node js server?

So this is my server.js:

const express = require("express");
const multer = require("multer");
const cors = require("cors");
const admin = require("firebase-admin");
const { v4: uuid } = require("uuid");

const serviceAccount = require("./serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  storageBucket: "mydb.firebasestorage.app"
});

const bucket = admin.storage().bucket();

const app = express();
app.use(cors()); // Middleware pentru CORS

const upload = multer({ storage: multer.memoryStorage() });

app.get("/upload", (req, res) => {
  res.send(`
    <html>
      <head>
        <title>Upload Imagine</title>
      </head>
      <body>
        <h1>Upload image</h1>
        <form method="POST" action="/upload" enctype="multipart/form-data">
          <input type="file" name="image" accept="image/*" />
          <button type="submit">Upload</button>
        </form>
      </body>
    </html>
  `);
});

app.post("/upload", upload.single("image"), async (req, res) => {
  console.log("req.body:", req.body);

  if (!req.file) return res.status(400).send("No file uploaded");

  let userId = req.body.userId;
  if (!userId) return res.status(400).send("Invalid user ID");

  userId = parseInt(userId, 10);
  if (!Number.isInteger(userId)) return res.status(400).send("Invalid user ID");

  try {
    const filename = `upload/${userId}/${uuid()}.png`;
    const file = bucket.file(filename);

    await file.save(req.file.buffer, { resumable: false });
    await file.makePublic();

    const downloadURL = `https://storage.googleapis.com/${bucket.name}/${filename}`;
    res.json({ imageUrl: downloadURL });
  } catch (error) {
    console.error("Error uploading file:", error);
    res.status(500).send("Upload failed");
  }
});

app.listen(3000, () => console.log("Server running on http://localhost:3000"));

The user scans a QR code and gets taken to that page where he is required to upload a photo.

This is the part of my React code that should give the userId to the server, but if I try to console.log it, it prints undefined:

const localIP = "myipv4address";
  const uploadUrl = `http://${localIP}:3000/upload`;

  const [userId, setUserId] = useState(null);


  useEffect(() => {
    const fetchUserData = async () => {
      const storedData = localStorage.getItem("auth");
      if (!storedData) return;

      const { email, password } = JSON.parse(storedData);
      try {
        const userResponse = await axios.get(
          `http://localhost:8080/users/byEmail/${email}`,
          {
            headers: { "Content-Type": "application/json" },
            auth: { username: email, password },
          }
        );

        setUserId(parseInt(userResponse.data.id,);
        console.log(userResponse.data.id);
      } catch (error) {
        console.error("Eroare la preluarea userului:", error);
      }
    };

    fetchUserData();
  }, []); // this part gets the userId from the backend in java, I console logged it and it has no problem

  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (!file) return;
  
    const allowedTypes = ["image/jpeg", "image/jpg", "image/png"];
    if (!allowedTypes.includes(file.type)) {
      setFileName("Invalid type of file!");
      event.target.value = "";
      return;
    }
  
    if (userId === null) {
      console.error("User ID invalid");
      return;
    }
  
    try {
      const formData = new FormData();
      formData.append("image", file);
      formData.append("userId", String(userId));
  
      const response = await fetch(uploadUrl, {
        method: "POST",
        body: formData,
      });
  
      if (!response.ok) throw new Error("Error");
  
      const data = await response.json();
      setFileName(file.name);
      setResultText(`Imagine uploaded: ${data.imageUrl}`);
    } catch (error) {
      console.error("Error:", error);
      setFileName("Error at upload");
      event.target.value = "";
    }
  }; // this is the part that should give the userId to the server.js, but when it arrives there, it is undefined

I tried everything that chatgpt and deepseek suggested at it doesn't work.

The funny thing is that if instead of userId = parseInt(userId, 10); I use userId = 12, which is my accounts id, it works fine, in Firebase I have the file uploaded at /upload/12/my file name.png

Upvotes: 0

Views: 88

Answers (0)

Related Questions