如何停止表单提交时的重定向,但仍然通过Multer POST到操作URL?

时间:2018-11-23 08:08:22

标签: html node.js express multer

我正在使用Multer将图像上传到服务器文件系统,而我遵循的教程建议采用如下形式的HTML设置:

<form action="/upload" id="myForm" name="myForm" enctype="multipart/form-data" method="post">
  <input id="myFile" name="myFile" type="file">
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

图像文件上传成功,但是用户将被重定向到“ / upload”。根据我的研究,Ajax无法处理图像上传,而Multer仍然需要enctype="multipart/form-data"属性。

我曾尝试设置快速路由以将用户重定向到上一页,但由于两个console.log()都未执行,因此似乎无法获得快速路由。这是我的代码:

 app.get("/upload", function(req, res){
   backURL = req.header('Referer') || '/';
   // need to display "Profile image updated!"
   console.log(backURL);
   console.log("none");
   res.redirect(backURL); 
 })

是否有一些方法可以停止重定向,但仍然POST到/ upload?

编辑:我忘了提到我也使用express将数据发布到/ upload:

  app.post('/upload', function (req, res) {
upload(req, res, (err) => {
  if (err) {
    console.log("problem at api-routes line 88")
    res.render('index', {
      msg: err
    });
  } else {
    if(req.file == undefined){
      res.render('index', {
        msg: 'Error: No File Selected!'
      });
    } else {
      db.User.update({
        profileImg: req.file.filename
      },{
        where: {
          id: req.user.id
        }
      }).then(function (dbPost) {
        //res.json(dbPost);
        res.render('index', {
          msg: 'File Uploaded!',
          file: `uploads/${req.file.filename}`
        });
      }).catch(function (err) {
        console.log(err);
        res.status(422).json(err.errors[0].message);
      });

    }
  }
})

})

1 个答案:

答案 0 :(得分:-1)

  

图像文件上传成功,但是用户将被重定向到“ / upload”。

当浏览器请求一个URL,但服务器说“您希望在另一个URL上获取它,取而代之”时,就会发生重定向。

您没有遇到重定向。 action只是告诉浏览器将数据提交到/upload


  

我曾尝试设置快速路由以将用户重定向到上一页,但由于两个console.log()都未执行,因此似乎无法获得快速路由。

您的路线通往get(),但您有method="POST"

要处理POST请求,您需要一个post()处理程序。实际处理表单提交的那个人!