Сервер отвечает неопределенным при загрузке файла, используя axios / fetch с multer - PullRequest
0 голосов
/ 24 сентября 2019

Вот что у меня было раньше и работает

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>

Однако, делая это так, я не могу получить ответ от сервера, и мне приходится делать res.redirect ('back'), чтобы "обновить" страницу, в противном случае страница продолжает ждать localhost с кружком загрузки в заголовкебар.После некоторых исследований я получил следующую информацию:

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));
};

Однако я продолжаю получать «неудачный» ответ от сервера из обеих выборокAPI и Axios.e.target.data.value возвращает C: /fakepath/test.csv.Я могу или не могу упускать из виду что-то очевидное, но был в этом в течение нескольких часов и до сих пор не могу понять, что не так.Пожалуйста, помогите мне пролить свет на этот вопрос, спасибо!

Ответы [ 2 ]

0 голосов
/ 24 сентября 2019

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));
};

попробуйте это вам поможет.

0 голосов
/ 24 сентября 2019

Я считаю, что multer должен передаваться как промежуточное ПО.Например:

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
})
...