Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native fetch "unsupported BodyInit type"

I'm trying to send a POST request to the OneSignal REST API using fetch:

var obj = {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    'app_id': '(API KEY)',
    'contents': {"en": "English Message"},
    'app_ids': ["APP IDS"],
    'data': {'foo': 'bar'}
  })
}

fetch('https://onesignal.com/api/v1/notifications', obj)

I know you're not really supposed to put your API key in client code, but this is just a test to see if it would work. Besides, the error I'm getting isn't a bad response from the server, it's:

Possible Unhandled Promise Rejection (id: 0):
unsupported BodyInit type

I've tried putting a catch method on the fetch, but it doesn't get called.

At a bit of a loss, not really sure how to proceed.

Thanks in advance!

like image 984
user2672053 Avatar asked Aug 20 '16 16:08

user2672053


2 Answers

Even I tried the same POST request for One-Signal REST API for creating notifications,the below worked for me fine.

const bodyObj = {
  app_id: "**********",
  included_segments: ["All"],
  data: {"foo": "bar"},
  contents: {"en": "Hi good morning"}
 }

  fetch('https://onesignal.com/api/v1/notifications',{
    method:'POST',
    headers:{
    'Authorization':'Basic **********',
    'Content-Type':'application/json'
   },
     body:JSON.stringify(bodyObj)
 })
   .then((response) => response.json())
   .then((responseJson) => {
    console.log("success api call");
  })
  .catch((error) => {
      console.error(error);
  }); 
like image 156
Thanmai C Avatar answered Sep 29 '22 02:09

Thanmai C


Have you tried to change your json to the one below?

JSON.stringify({
  app_id: '(API KEY)',
  contents: {en: "English Message"},
  app_ids: ["APP IDS"],
  data: {foo: 'bar'}
})

Or even tried a simpler json?

like image 34
Igor Regis Avatar answered Sep 29 '22 01:09

Igor Regis