SHAI
SHAI

Reputation: 859

How to send a post request on Typescript?

I have this code but I need to translate it to Typescript, and having issues finding the request module

function sendNotificationToUser(username, message, onSuccess) {
request({
  url: 'https://fcm.googleapis.com/fcm/send',
  method: 'POST',
  headers: {
    'Content-Type' :' application/json',
    'Authorization': 'key='+API_KEY
  },
  body: JSON.stringify({
    notification: {
      title: message
    },
    to : '/topics/user_'+username
  })
}, function(error, response, body) {
  if (error) { console.error(error); }
  else if (response.statusCode >= 400) { 
    console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage); 
  }
  else {
    onSuccess();
  }
});

}

Upvotes: 0

Views: 10939

Answers (1)

Blazkowicz
Blazkowicz

Reputation: 195

    const response = await fetch("https://fcm.googleapis.com/fcm/send", {
      method: 'POST',
      body: JSON.stringify({notification: {title: message},to : '/topics/user_'+username}),
      headers: {'Content-Type': 'application/json', 'Authorization': 'key='+API_KEY} 
    });
    
    if (!response.ok) 
    { 
        console.error("Error");
    }
    else if (response.statusCode >= 400) {
        console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
    }
    else{
        onSuccess();
    }

Upvotes: 2

Related Questions