除了使用Axios和NodeJS的文件外,FormData不会附加其他变量 [英] FormData doesnt append other variables except file using Axios and NodeJS

查看:69
本文介绍了除了使用Axios和NodeJS的文件外,FormData不会附加其他变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在尝试通过Axios PATCH方法发送我的FormData并在NodeJS服务器端接收它.当我在NodeJS中执行console.log时,不知何故它不会接收已发送的任何参数.是因为我的格式错误还是怎么办?我还将身体解析器添加到NodeJS代码中.

Currently, I am trying to send my FormData through Axios PATCH method and receive it on NodeJS server-side. Somehow it won't receive any parameters that have been sent when I do a console.log in NodeJS. Is it because I have it in a wrong format or how? I also have added body-parser to the NodeJS code.

UserEdit.js

submitEdit = () =>{
    const { user, user_id, usernameInput, firstnameInput, lastnameInput, imageInput, emailInput, relogin, selectedFileName } = this.state

    console.log(selectedFileName);

    const data = new FormData();
    data.append('file', this.state.selectedFile);
    data.append('usernameInput', usernameInput);
    data.append('firstnameInput', firstnameInput);
    data.append('lastnameInput', lastnameInput);
    data.append('emailInput', emailInput);
    data.append('imageInput', selectedFileName);
    data.append('user_id', user.user_id);

const config = {
      headers: {
          'content-type': 'multipart/form-data'
      }
  };
    
axios.patch(`/users/edit/${user.user_id}`, data, config)      
    .then(res => {
      console.log(res.statusText)
   })
}

app.js

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const storage = multer.diskStorage({
  destination: "./../frontend/src/images/uploads/",
  filename: function(req, file, cb){
     cb(null,"IMAGE-" + file.originalname);
  }
});

const upload = multer({ storage: storage }).single('file');

app.patch('/users/edit/:userID', (req, res) => {
  console.log(req.body);
  const text = 'UPDATE users SET (username, email, first_name, last_name, user_img) = ($1, $2, $3, $4, $5) WHERE user_id=($6)'
  const values = [req.body.username, req.body.email, req.body.first_name, req.body.last_name, "IMAGE-" + req.body.imageInput, req.body.user_id];

  db.query(text, values)
       .then(() => {
        console.log("success!");
        // success;
      })
      .catch(error => {
        console.log(error);
});
  upload(req, res, (err) => {
    if (err) {
      res.sendStatus(500);
    }
    res.send(req.file);
  });
});

推荐答案

为减少错误,请与邮递员一起使用发送请求,如果请求正确,请执行3个步骤,例如photo,然后复制Nodejs的更新代码-axios

To reduce your mistake, use a send request with postman, if your request is right, do 3 steps like photo, and copy gerenated code foor Nodejs-axios

我认为您的问题与 header 有关,您可以检查代码中的请求并将其与邮递员的请求进行比较

I think your problem is about header, you can check and compare your request in code with request from postman

这篇关于除了使用Axios和NodeJS的文件外,FormData不会附加其他变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆