0

Working on my first MERN stack application. I'm trying to make an axios post request from my React client (port 3000) to my MongoDB API (port 3001). My post request code is:

<button
        onClick={() => {
          axios({
            method: "post",
            url:
              "http://localhost:3000/api/update/documentID",
            data: { newNumber: 12345 },
            headers: { "Content-Type": "application/x-www-form-urlencoded" }
          });
        }}
      >
        Click to run axios post request
</button>

This results in a body showing up on my port 3001 server as:

body: { '{"newNumber":12345}': '' }

I have my React proxy server set up and body-parser installed on my port 3001 server. I'm able to make the exact request I want using Postman. I can also get exactly what I want by replacing my Button in React with a Form, but obviously having to submit a form to make a post request isn't ideal.

(Also, if I try to use axios.post(etc) instead of axios({ method: post, etc.), I end up with an entirely empty body.

Any help would be appreciated.

1
  • WARNING: If you're using Postman, ensure the request has properly set the Content-Type: application/json and using the raw format in the Body tab and not the x-www-form-urlencoded. Commented Aug 24, 2021 at 14:07

1 Answer 1

1

Answered my own question, changed

headers: { "Content-Type": "application/x-www-form-urlencoded" }

to

headers: { "Content-Type": "application/json" }

and it worked.

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.