Fierid Neil
Fierid Neil

Reputation: 45

Server responds undefined when upload file using axios/fetch with multer

Here's what I have before and it's working

server.js

const storage = multer.diskStorage({
    destination: (req, res, cb) => {
        cb(null, "./uploads");
    },
    filename: (req, res, cb) => {
        cb(null, res.originalname);
    }
});
const upload = multer({ storage: storage }).single("data");
app.post("/upload", (req, res) => {
    console.log(req.file);
    upload(req, res, err => {
        if (err) throw err;
        if (req.file) {
            console.log("Uploaded");
            // Refresh the page
            // res.redirect("back");
            res.send("uploaded");
        } else {
            console.log("Failed");
            res.send("failed");
        }
    });
});

App.js

<form
      action='http://localhost:3001/upload'
      method='POST'
      encType='multipart/form-data>
      <div>
          <input type='file' name='data' />
      </div>
      <div>
          <button type='submit'>Submit</button>
      </div>
  </form>

However doing it like this doesn't allow me to receive server response and I have to do res.redirect('back') to "refresh" the page, otherwise the page keeps waiting for localhost with a loading circle on title bar. After some research, I got the following on react side:

App.js

    const FormSubmitHandler = e => {
    e.preventDefault();
    console.log(e.target.data.value);
    const form_data = new FormData();
    form_data.append("data", e.target.data.value);
    axios
        .post(`http://localhost:3001/upload`, e.target.data.value)
        .then(res => console.log(res))
        .catch(err => console.log(err));

    // console.log(form);
    // fetch("http://localhost:3001/upload", {
    //     method: "POST",
    //     body: form_data
    // })
    //     .then(res => res.text())
    //     .then(res => console.log(res))
    //     .catch(err => console.log(err));
};

However I keep getting 'failed' response from the server from both fetch api and axios. e.target.data.value returns C:/fakepath/test.csv. I may or may not overlook something obvious but been at this for hours and still cannot figure out what's wrong. Please help me shed some light on this matter, thanks!

Upvotes: 0

Views: 685

Answers (2)

Prakash Karena
Prakash Karena

Reputation: 2605

server.js

const storage = multer.diskStorage({
    destination: (req, res, cb) => {
        cb(null, "./uploads");
    },
    filename: (req, res, cb) => {
        cb(null, res.originalname);
    }
});
const upload = multer({ storage: storage }).single("data");
app.post("/upload", upload , (req, res) => {
        if (err) throw err;
        if (req.file) {
            console.log("Uploaded");
            // Refresh the page
            // res.redirect("back");
            res.send("uploaded");
        } else {
            console.log("Failed");
            res.send("failed");
        }
    });
});

App.js

const FormSubmitHandler = e => {
    e.preventDefault();
    const form_data = new FormData();
    form_data.append("data", e.target.files[0]); //changes
    axios
        .post(`http://localhost:3001/upload`, form_data ) //changes
        .then(res => console.log(res))
        .catch(err => console.log(err));

    // console.log(form);
    // fetch("http://localhost:3001/upload", {
    //     method: "POST",
    //     body: form_data
    // })
    //     .then(res => res.text())
    //     .then(res => console.log(res))
    //     .catch(err => console.log(err));
};

try this will help you.

Upvotes: 1

Shihab
Shihab

Reputation: 2679

I believe multer should be passed as middleware. For example:

const upload = multer({ dest: 'uploads/' });
app.post('/profile', upload.single('data'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

Upvotes: 0

Related Questions