0

I am unable to post the data to the server and getting a timeout error. Please see the code below:

Client side script:

    $(document).ready(function(){
            $('#form1').on('submit',function(e) {
                e.preventDefault();
                    $.ajax({
                    type: "POST",
                    url: "/",
                    timeout: 2000,
                    data : JSON.stringify({ image: "yo", text: "apples" }),
                    dataType : 'json',
                    success: function(data) {
                        alert('Success!')
                    },
                    error: function(jqXHR, textStatus, err) {
                        alert('text status '+textStatus+', err '+err)
                    }
            });
            })
    })

Server side script :

    app.use(bodyParser.json());
    app.post('/', function (req, res){

        console.log(req.body);
        console.log('req received');

    });

On the server I am seeing the output as

    APP STARTED ON PORT - 3000
    {}
    req received

Can you please guide me for why I am unable to receive the data ? Thank you in advance.

METALHEAD
  • 2,734
  • 3
  • 22
  • 37

2 Answers2

1

The reason you're getting timeout is that you are not responding to the request. Even if your api does not have any result you should respond to the request, at least with a status code.

res.sendStatus(200);

body-parser by default only parses requests that have content-type of application/json. Try adding contentType: 'application/json; charset=UTF-8' to jQuery ajax options.

$.ajax({
    ...
    contentType: 'application/json; charset=UTF-8',
    ...
});
Shant Marouti
  • 1,295
  • 7
  • 11
0

Body is always sent as an object....don't stringify it!

p u
  • 1,395
  • 1
  • 17
  • 30