将数据发送到 mongodb 领域会出现 400 错误

Sending data to mongodb realm gives 400 error

我正在尝试使用以下代码post 将用户数据从我的应用程序 api

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);
    });
  }

我的应用程序在 mongodb 领域中 运行,我的 webhook 如下所示:

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  {};
};

我已经测试了 webhook,它在 mongodb 控制台上运行,但我无法在应用程序内部运行它。无论我使用什么方法,我都会收到 POST 400 错误。 我的完整代码在这里 https://github.com/Imstupidpleasehelp/MERN-lesson 提前感谢您的帮助,我已经坚持了一段时间

这不是一个解决方案,更像是一种变通方法,但在使用 axios 时我没有收到错误,api 工作正常。 我的新代码给任何感兴趣的人

  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);
    });
   
  }

我重新创建了这个,但也遇到了 400 错误,消息是:

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

这让我觉得发送的请求格式有问题,所以我查看了 docs,他们说 json 请求的主体必须转换为 json 首先是 JSON.stringify。他们的例子:

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);
});

之后一切正常。