javascript 我想在Axios处于react-native时发布FCM通知,但它抛出错误400“Axios错误”

l7mqbcuq  于 2023-01-11  发布在  Java
关注(0)|答案(2)|浏览(107)
// function  for FCM notification

const onSendMassage = async (fcmtoken) => {
  console.log(fcmtoken, "fcm here");

  const notifications = {
    notification: [
      {
        title: "Hola!",
        body: "Hello World",
        icon: "https://xxxx.com/icon.png",
        click_action: `https://example.com/`,
      },
    ],
    to: fcmtoken,
  };

  // axios api hit

  axios
    .post(
      "https://fcm.googleapis.com/fcm/send",
      { notifications },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: "key= mykey",
        },
      }
    )
    .then((response) => {
      console.log("response" + response);
    })
    .catch((error) => {
      console.log(error, "errr");
    });
};
t98cgbkg

t98cgbkg1#

400代码意味着服务器无法解析json数据,可以尝试将通知作为对象而不是数组发送,这应该可以解决您的问题

const notifications = {
    notification: [
      {
        title: "Hola!",
        body: "Hello World",
        icon: "https://xxxx.com/icon.png",
        click_action: `https://example.com/`
      }
    ],
    to: fcmtoken
  };
cnwbcb6i

cnwbcb6i2#

有四个问题我看到初学者做得太频繁了...
1.未阅读文档
1.将所有内容记录到控制台(并误解结果)
1.不必要地设置请求标头
1.无缘无故地把所有东西都用大括号括起来
{ notifications }{ "notifications": notifications }相同,这不是legacy REST API所期望的。
notification属性也作为对象而不是数组列出
| 参数|用途|说明|
| - ------| - ------| - ------|
| * * 一米三米一x**|可选,对象|此参数指定通知负载的预定义、用户可见的键值对......。|
您可能希望使用以下命令...

const downstream = {
  notification: {
    title: "Hola!",
    body: "Hello World",
    icon: "https://example.com/icon.png",
    click_action: `https://example.com/`,
  },
  to: fcmtoken,
};

axios
  .post("https://fcm.googleapis.com/fcm/send", downstream, {
    headers: { authorization: "key= mykey" },
  })
  .then(console.log)
  .catch(console.error);

相关问题