node.js - NodeJS Ajax 请求失败

标签 node.js ajax express

我正在尝试从客户向 Express 提交一个表单,但每次我都会收到如下错误:

Cannot POST /request_method

下面是我正在尝试的代码:

index.html

<form id="wizard-content" method="post">
   <label>File</label>
   <input type="file" name="some" id="rsome">
   <label>Value</label>
   <input type="text" name="valSome" id="perfect">
</form>
<button type="submit" id="submit_form">Finish</button>
    <script type="text/javascript">
        jQuery('#submit_form').click(function() {
            if (jQuery(this).text().toLowerCase() === "finish") {
                submitForm();
            }
        });
        var submitForm = function(){
            var formData = {
                    'perfect'        : $('#perfect').val(),
                    'rsome'            : $('#rsome')[0].files[0]
                };
            if(formData){
                $.ajax({
                    url : '/request_method',
                    type : 'POST',
                    data : formData,
                    contentType : false,
                    cache : false,
                    processData: false,
                    success : function(response){
                        console.log(response);
                    }, 
                    error : function(error){
                        console.log(error);
                    }
                });
            }
        }
    </script>

在expressJs中:

server.js

var express     = require('express');
var bodyParser  = require('body-parser')
app.use(bodyParser());
.
.
router.post('/request_method', function(req, res){
   console.log(req.body);
   console.log(req.ip);
});

最佳答案

您的应用可能未使用您已设置的路由器

两种解决方案

1 - 使用您的应用而不是路由器定义路线

app.post('/request_method', function(req, res){
   console.log(req.body);
   console.log(req.ip);
});

2 - 或使用路由器

router.post... 之前添加以下行,这将告诉您的应用程序使用 router 中定义的路由。

app.use('/', router);

关于node.js - NodeJS Ajax 请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43998414/

相关文章:

javascript - AJAX 函数未触发

jquery - 无法将变量添加到 success 函数

node.js - 修改代理请求的 header

javascript - 如何在 Node 环境中使用 Puppeteer 创建 PDF 而无需将其写入磁盘

node.js - Connect2 和 Socket.io

javascript - Node.js将json数组对象插入mysql表

node.js - 在 mongodb forEach 循环查询后在 SailsJS 中渲染 View

c# - Ajax 工具包文件上传未调用

node.js - 如何在 NodeJs 中扩展 express js res 对象

javascript - Express 4 FormData多部分解析POST请求