0

I've Tried uploading some file by multer.diskStorage but got an error for this by axios that it cannot proxy the frontend to backend host address. The Error Only Occurs When I'm sending the FormData to the server, else No Proxy Error... The axios post request says that Could not proxy request ${ROUTE} from localhost:3000 (React Host) to http://localhost:8800/ (Express Host) and showing the error (ECONNRESET).

I've used a comment to show THE PROBLEM PART. Hoping for a solution...

Here is my react's package.json file

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@mui/icons-material": "^5.11.0",
    "@mui/material": "^5.11.2",
    "@mui/styled-engine": "^5.11.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.2.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router": "^5.3.4",
    "react-router-dom": "^5.3.4",
    "react-scripts": "5.0.1",
    "timeago.js": "^4.0.2",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:8800"
}

This is my React Component (like FaceBook Share)

import './share.css'
import { Mood, CameraAlt, LocationOn, Label, ArrowDropDown } from '@mui/icons-material';
import { useContext, useRef, useState } from 'react';
import { AuthContext } from '../../context/AuthContext'
import axios from 'axios';

const Share = () => {
    const { user } = useContext(AuthContext);
    const [file, setFile] = useState(null);
    const desc = useRef();

    const submitHandler = async (e) => {
        console.log("..............................");
        e.preventDefault();
        const newPost = {
                userId: user._id,
                desc: desc.current.value
            }
        if (file) {    // THIS IS THE PROBLEM PART
            const data = new FormData();
            const fileName = file.name + Date.now();
            data.append('file', file);
            data.append('name', fileName);
            newPost.img = fileName;
            try {
                axios.post('/upload', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                    transformRequest: formData => formData,
                })
                .then((res) => {
                    console.log(res.data);
                });
            } catch (err) {
                console.log(err);
            }
        }
        try {
           await axios.post('/posts/', newPost);
        }catch(err){}
    }

    const PF = process.env.REACT_APP_PUBLIC_FOLDER;

    return (
        <div className='share'>
            <div className="shareTop">
                <div className='shareProfileContainer'>
                    <img src={user.profilePicture || PF+'content/noAvatar.png'} alt="Profile" className="shareProfile" />
                    <div className='shareDetails'>
                        <span className='shareProfileText'>{user.username}</span>
                        < ArrowDropDown className='shareProfileOption' />
                        <span className='shareProfileOptionText'>Public</span>
                    </div>
                </div>
                <input placeholder={"What's on your mind, " + user.username + '?'} className='shareInput' ref={desc}/>
            </div>
            <hr className='shareHr' />
            <div className="shareBottom">
                <form className="shareOptions" onSubmit={submitHandler} enctype="multipart/form-data" name="file">
                    <label htmlFor='photosNvideos' className="shareOption">
                        < CameraAlt color='success' />
                        <input id='photosNvideos' type="file" accept='.png, .jpg, .jpeg, .heif, .mp4, .hevc' onChange={(e) => (setFile(e.target.files[0]))} />
                        <span className='shareOptionText'>Photo/Video</span>
                    </label>
                    <div className="shareOption">
                        < LocationOn color='error' />
                        <span className='shareOptionText'>Location</span>
                    </div>
                    <div className="shareOption">
                        < Label color='primary' />
                        <span className='shareOptionText'>Tag</span>
                    </div>
                    <div className="shareOption">
                        < Mood color='warning' />
                        <span className='shareOptionText'>Feeling</span>
                    </div>
                    <button type="submit" className="shareButton">Post</button>
                </form>
            </div>
        </div>
    );
}

export default Share;

And This is my backend code

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const multer = require('multer');
const path = require('path');

dotenv.config();

mongoose.set('strictQuery', true);
mongoose.connect(process.env.DB_URL, () => {
    console.log('Connected to MongoDB');
});

app.use('/images', express.static(path.join(__dirname, './public/images')));

//middleware
app.use(express.json());
app.use(morgan('common'));

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images');
    },
    filename: function (req, file, cb) {
        cb(null, req.body.name);
    }
});

const upload = multer({ storage });
app.post('/upload', upload.single("file"), (req, res) => {
    try {
        return res.status(200).json("Upload Success");
    } catch (err) {
        console.log(err);
    }
});

app.use('/users', userRoute);
app.use('/posts', postRoute);
app.use('/auth', authRoute);

app.listen(8800, () => {
    console.log('Backend server is running!');
});

I've Tried uploading some file by multer.diskStorage but got an error for this by axios that it cannot proxy the frontend to backend host address.

0 Answers0