Empty Node.js/Express response

16,083

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

Share:
16,083
Ricardo Magalhães Cruz
Author by

Ricardo Magalhães Cruz

MS in Applied Mathematics BS in Computer Science

Updated on August 21, 2022

Comments

  • Ricardo Magalhães Cruz
    Ricardo Magalhães Cruz over 1 year

    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.