Wednesday, 26 May 2021

Sending data to mongodb realm gives 400 error

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



from Sending data to mongodb realm gives 400 error

No comments:

Post a Comment