Note that there are some explanatory texts on larger screens.

plurals
  1. POJQuery ajax fails on POST to express.js server
    text
    copied!<p><strong>The main problem seems to be</strong> that jQuery is sending the following header in the AJAX request:</p> <pre><code>POST http://localhost:3000/enter HTTP/1.1 </code></pre> <p>, while it should be</p> <pre><code>POST /enter HTTP/1.1 </code></pre> <p><strong>In more detail, this is how my server and client are set up and the exact requests and responses:</strong></p> <p>I have a pretty simple setup with <code>express.js</code> on the server and <code>jQuery</code> on the client. All I need is a POST request to the server.</p> <p>This is, more or less, what the server looks like:</p> <pre><code>app.post('/enter', function(req, res){ console.log(req.body) res.json({flag: true}) }) </code></pre> <p>Here's what the jQuery looks like:</p> <pre><code>$.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) } }) </code></pre> <p>Surely enough, the server's <code>console.log</code> confirms the correct data. The alert message I get after the AJAX is simply <code>text status error err</code>.</p> <p>Chrome tells me the request headers are:</p> <pre><code>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/? </code></pre> <p>The response to that request is:</p> <pre><code>HTTP/1.1 0 undefined </code></pre> <p>I also used telnet to gain some clarity into the situation. In telnet, I see the response is:</p> <pre><code>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 </code></pre> <p>So the problem seems to be the line <code>POST http://localhost:3000/enter HTTP/1.1</code>. If I send the headers with that line changed to <code>POST /enter HTTP/1.1</code>, it works perfectly!</p> <p>I'm using Chrome 15 on Ubuntu 11. I've also tried it with Firefox 9.</p> <p>Thanks in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload