如何使用Node.js处理不正确的POST请求? [英] How to handle an incorrect POST request using Node.js?

查看:141
本文介绍了如何使用Node.js处理不正确的POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL; DR
表单使用"data/fileUpload"提交POST请求.
服务器响应200并呈现一个新页面.好东西.

TL;DR
Form submits a POST request with "data/fileUpload".
Server responds 200 and renders a new page. Goody.

尝试再次在呈现的页面中上传新文件.
POST请求现在为"data/fileUpload/fileUpload".
服务器不知道该怎么办.爸爸.

Try to upload a new file in the rendered page again.
POST request is now "data/fileUpload/fileUpload".
Server doesn't know what to do. Baddy.

我不确定发生了什么,这就是标题很模糊的原因.我正在为Node(Express)应用程序实现一个简单的功能. 这是此功能的作用:

I am not exactly sure what is going on, that's why the title is very vague. I am implementing a simple feature to a Node (Express) application. Here is what this feature does:

  • 用户上传文件.
  • 用户提交文件以供审核.
  • 用户收到回复.

问题

上传文件并返回结果功能可以顺利进行.在文件被上传并且服务器呈现新页面之后,浏览器仍然位于"data/fileUpload"位置.网址.尝试上传第二个文件会将POST请求定向到以下网址"data/fileUpload/fileUpload".服务器无法路由.

Uploading a file and returning a result functionality works smoothly. After file is uploaded and the server renders a new page, browser is still at "data/fileUpload" url. Trying to upload a second file directs a POST request to the following url "data/fileUpload/fileUpload" which can not be routed by the server.

<!DOCTYPE html>
    <!-- Boilerplate ... -->
    <body
    <div id="form">
         <%= message %>
         <% if(processed == "true"){ %>
         <%= results %>
         <% }; %>
         <form method='post' action='data/fileUpload' enctype="multipart/form-data">
            <input type='file' name='fileUploaded' id="browseButton" required>
            <input type='submit' value="Upload" id="uploadButton">
      </div>
     <script>
        var uploadField = document.getElementById("browseButton");
        uploadField.onchange = function() {
            if(this.files[0].size > 2097152){
            alert("File is too big!");
            this.value = "";
            };
        };
</script>
</body>
</html>

如您所见,表单动作是"data/fileUpload".此发布请求由以下路由器和控制器处理.

As you can see the form action is "data/fileUpload". This post request is handled by the following router and controllers.

// Defined in app.js
app.use('/data',  dataRouter); 

以下路由器位于data.js中. processController是从processData.js控制器导入的.

The following Router is in data.js. processController is imported from processData.js controller.

router.post('/fileUpload', [processController.fileUpload, processController.process]);

这是用于文件上传和处理的控制器.

And this is the Controller for fileUpload and process.


exports.fileUpload = function(req, res,next) {
   // Upload the file... 
   next(); // calls process function
};

// Process the data. Not implemented
exports.process = function(req, res) {
        res.render('index', {processed:"true", 
            message: "hello", results:"result" });
    });
};

以下是不完整的目录树.
├──app.js
├──控制器
│└──processController.js
├──package.json
├──路线
│├──data.js
├──上传文件
│└──Uploaded.file
└──意见
├──index.ejs


The following is the incomplete directory tree.
├── app.js
├── controllers
│ └── processController.js
├── package.json
├── routes
│ ├── data.js
├── uploads
│ └── Uploaded.file
└── views
    ├── index.ejs


如何使服务器返回初始页面并发送结果?

How can I enable server to go back to the initial page but also send results?

推荐答案

您应结合使用res.redirect()

You should use res.redirect() combined with req.flash() - connect flash (that at some point got excluded from expressjs bundle) for what you are trying to do. (Which is sending an ok/not-ok message back to front).

res.render()将html(或任何其他引擎)模板发回前端并进行渲染-它不在乎接下来会发生什么,这可能会导致诸如您的问题(将整个页面作为模板发送并弄乱数据) ).

res.render() Sends back an html (or any other engine) template back to front and renders - It does not care for what happens next and this can cause problems such as yours (sending a full page as template and messing up data).

res.redirect()将用户重定向到另一条路由(通过重新启动请求,例如:GET /some_new_or_even_the_same_route.

res.redirect() redirects the user to another route (by this restarting the request like: GET /some_new_or_even_the_same_route.

req.flash()可以处理返回的消息.

req.flash() Can handle returned messages.

此外,使用redirect(),您可以发送状态代码作为第一个参数,该参数可以用作您的processed true/false

Also, with redirect() you could send a status code as the first argument which can act as your processed true/false

我认为res.render()并不是在您的方案中使用的正确功能.

I think res.render() is just not the right function to use in your scenario.

这篇关于如何使用Node.js处理不正确的POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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