0

I can't figure out why this problem is arising. When I make an ajax post request in my javascript file, the url gets called, but the data wont get sent. Here's how I make a post request:

<script type="text/javascript">
    $.ajax({
        type: "POST",
        url: "/test",
        dataType: "json",
        data: {test: "test"},
        contentType: "application/x-www-form-urlencoded",

    });
</script>

And on my backend, here's the post method I'm using:

app.post('/test', function(req, res) {
  console.log(req.body); // returns {}
  console.log(req.params); // returns {}
});

Here's what I tried so far: XMLHttpRequest to Post HTML Form, AJAX Post not sending form data , Send POST data using XMLHttpRequest but unfortunately none of them worked for me.

12
  • 1
    you can remove the contentType option, that's not necessary for what you're doing. (the default will suffice) Commented May 1, 2017 at 19:53
  • You're sure you're hitting your endpoint? You're seeing stuff in your console on the server-side whenever you send an AJAX request? Have you tried doing console.log(req) to see if the data is on a different property? Commented May 1, 2017 at 19:53
  • try JSON.stringify({test: "test"}) Commented May 1, 2017 at 19:53
  • @KevinB I've tried it without contentType too, still doesn't work. Any other suggestions? Commented May 1, 2017 at 19:54
  • you have to send some response to FE right? res.send('something') ?? otherwise that request will get timedout in browser Commented May 1, 2017 at 19:54

1 Answer 1

1

dataType: "json" expects data in JSON, but contentType: "application/x-www-form-urlencoded" sends data in different way. Maybe you should write dataType: "json", contentType: "application/json" or dataType: "html", contentType: "application/x-www-form-urlencoded"?

Sign up to request clarification or add additional context in comments.

Comments

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.