Sending data to mongodb realm gives 400 error

Viewed 694

I am trying to post user data to my api from my application with the following code

const submitPet = (e) => {
    e.preventDefault();
   let data = {
     pet: petName,
     breed: petBreed,
     image: petImage,
     desc: petDesc,
     user: props.user
   }
   
    fetch('https://us-west-2.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/my_pets-dbdsd/service/pets/incoming_webhook/addnewpet', {
      method: 'POST',
      body: data,
      headers: {
        'Content-type': 'application/json; charset=UTF-8'
      }
    }).then(function (response) {
      if (response.ok) {
        return response.json();
      }
      return Promise.reject(response);
    }).then(function (data) {
      console.log(data);
    }).catch(function (error) {
      console.warn('Something went wrong.', error);
    });
  }

My application is running in mongodb realm, and my webhook looks like so:

exports = async function(payload, response) {

  if (payload.body) {
      const body =  EJSON.parse(payload.body.text());
      const reviews = context.services.get("mongodb-atlas").db("pets").collection("my_pets");
      
      const reviewDoc = {
          name: body.name,
          user_id: body.user_id,
          date: new Date(),
          text: body.text,
          
      };
  
      return await reviews.insertOne(reviewDoc);
  }

  return  {};
};

I've tested the webhook and it works from the mongodb console, I just can't get it to work from inside the application. No matter what method I use I get a POST 400 error. My full code is here https://github.com/Imstupidpleasehelp/MERN-lesson I appreciate your help in advance, I have been stuck on this for a while

2 Answers

This isn't a solution as more of a workaround, but when using axios I do not receive the error and the api works just fine. My new code for anyone interested

  const submitPet = (e) => {
    e.preventDefault();
   let data = {
     pet: petName,
     breed: petBreed,
     image: petImage,
     desc: petDesc,
     user: toString(props.user)
   }
   
    //'https://us-west-2.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/my_pets-dbdsd/service/pets/incoming_webhook/addnewpet'
    axios
    .post(
      "https://us-west-2.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/my_pets-dbdsd/service/pets/incoming_webhook/addnewpet",
      data
    )
    .then((response) => {
      console.log(response);
    });
   
  }

I recreated this and got a 400 error as well, with the message:

error: {"message":"invalid character 'o' looking for beginning of value","name":"TypeError"}
error_code: FunctionExecutionError

It made me think something was wrong with the format of the request sent, so I looked at the docs and they say that the body of a json request must be converted to json first with JSON.stringify. Their example:

const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

After that it worked fine.

Related