NodeJS Ajax请求失败

我有一个表单,我试图从客户端提交到Express,但每次我得到一个错误,如:

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

您的app可能不使用您已经使用的router

两个解决scheme

1 – 使用您的应用程序而不是您的路由器来定义路线

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

2 – 或使用您的路由器

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

 app.use('/', router); 

你应该包括这样的bodyParser,

 // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) 

要么

 // parse application/json app.use(bodyParser.json()) 

试试:

 var submitForm = function(){ var formData = new FormData($('#wizard-content')[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); } }); } } 

在你的路线,使用req.files[0]来获取文件input

我犯了一个非常愚蠢的错误,我忘了添加使用路由器的URL。

 app.use('/', router);