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.

4
  • remove the JSON.stringify in the data prop Commented Aug 14, 2018 at 7:07
  • Possible duplicate of How to send data from JQuery AJAX request to Node.js server Commented Aug 14, 2018 at 7:09
  • @AmitWagner... I am getting the same error Commented Aug 14, 2018 at 7:19
  • What is complete url, you send from ajax call? Commented Aug 14, 2018 at 7:21

2 Answers 2

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',
    ...
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

If I do not stringify the object, shouldn't I use bodyParser at the server side..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.