I have a POST request that I want to process:
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser());
. . .
app.post('/signup', function(req, res) {
console.log('name: ' + req.body.name);
console.log('email: ' + req.body.email);
. . .
});
All seems well and dandy.
My client:
<html><body>
<form>
Name:<br>
<input type="text" name="name"><br>
Email:<br>
<input type="text" name="email"><br>
<input id="submit" type="submit" value="Submit">
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
$('input#submit').click(function() {
$.ajax({
url: 'http://localhost:5000/signup',
type: 'post',
dataType: 'json',
data: $('form').serialize(),
success: function(data) {
console.log('response:', data);
}
});
return false;
});
</script></body></html>
The problem? success
is never called in the client. Eventually, Chrome JS-debug window shows: net::ERR_EMPTY_RESPONSE
.
I have tried doing res.send(200)
, res.send('')
and res.end()
in the server, but without success.
My Node.js version is 4.2.6, and I think my Express version is 4.4.1.
jQuery Docs
dataType - The type of data that you're expecting back from the server;
data - Data to be sent to the server;
So, your frontend application expect a valid JSON back, but primaries (string, number, boolean) aren't a valid JSON, they have to be converted.
In order to perform this on fly:
res.json('success');
or
res.status(200).json('success');
If you want to stick with send method, you could write:
res.send(JSON.stringify('success'));
Also, sometimes this problem is related to ipconfig in windows and network connection
can you try this,
$.post('http://localhost:5000/signup', $('form').serialize(), function(data) {
console.log(data);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.