jQuery ajax在POST上失败express.js服务器

主要的问题似乎是 ,jQuery在AJAX请求中发送以下头文件:

POST http://localhost:3000/enter HTTP/1.1 

,而应该是

 POST /enter HTTP/1.1 

更详细地说,这是我的服务器和客户端的设置以及确切的请求和响应:

我有一个非常简单的设置与服务器上的express.js和客户端上的jQuery 。 我需要的只是一个POST请求到服务器。

这或多或less是服务器的外观:

 app.post('/enter', function(req, res){ console.log(req.body) res.json({flag: true}) }) 

以下是jQuery的样子:

 $.ajax( { url: '/enter' , type: 'POST' , cache: false , data: { field1: 1, field2: 2 } , success: function(data){ alert('Success!') } , error: function(jqXHR, textStatus, err){ alert('text status '+textStatus+', err '+err) } }) 

当然,服务器的console.log确认正确的数据。 我在AJAX之后得到的警报消息只是text status error err

Chrome告诉我请求标题是:

 POST http://localhost:3000/enter HTTP/1.1 Origin: http://localhost:3000 X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.2 (KHTML, like Gecko) Ubuntu/11.10 Chromium/15.0.874.106 Chrome/15.0.874.106 Safari/535.2 Content-Type: application/x-www-form-urlencoded Accept: */* Referer: http://localhost:3000/? 

对此要求的回应是:

 HTTP/1.1 0 undefined 

我也用telnet来了解情况。 在telnet中,我看到的回应是:

 404 Not Found X-Powered-By: Express Content-Type: text/plain Connection: keep-alive Transfer-Encoding: chunked 28 Cannot POST /http://localhost:3000/enter 0 

所以这个问题似乎是POST http://localhost:3000/enter HTTP/1.1 。 如果我发送的那一行的头文件改为POST /enter HTTP/1.1 ,那就完美了!

我在Ubuntu 11上使用了Chrome 15,我也用Firefox 9试了一下。

提前致谢!

这似乎与奇怪地提交表格的方式有关。

我误解了<button>标签的语义,试图用我的forms来使用它:

 <form> <button id="enter">Enter</button> </form> 

我创build了这样的事件处理程序:

 $('#enter').click(function(){ /* AJAX stuff... */ }) 

当我将HTML更改为

 <form> <input type="button" id="enter" value="Enter"> </form> 

,它工作正常。

但是,我不完全清楚为什么会造成这些错误。 这似乎与button提交表单的事实有关。 如果有人能向我解释这一点,我会很感激。

无论哪种方式,谢谢你的回应!

你需要在你的button元素中定义type属性,这样它的行为就像一个buttoninputtypes,就像这样:

 <button id="enter" type="button">Enter</button> 

大多数浏览器的默认buttontypes是“提交”。 但是这并不能保证,所以指定一个types总是一个好主意。