Javascript Fetch API

Is anyone familiar with the fetch api and making a post request to the photon?
I am looking for how to structure the request.

Here is an example of the syntax:

    fetch(url, {  
    method: 'POST',  
    headers: {  
      'auth': '1234'  
    },  
     body: JSON.stringify({
    name: 'dean',
    login: 'dean',
  })
})
.then(function (data) {  
  console.log('Request success: ', data);  
})  
.catch(function (error) {  
  console.log('Request failure: ', error);  
});

It bascially looks like a POST request… reading the docs on webhooks might help.

So here is my code I can’t get to work. I have read the docs a few times and am still not grasping this. I know the programming on the photon is good, as it works with some javascript and ajax on web page. I just need to use the javascript fetch call for another project.

Any suggestions?

var appHeading = "Led Control";

var core1ID = "53ff6a06666757482439xxxx";

var accessToken = "8b83c6bddbf8c73f0e835362cff88exxxxxxxxx";
var baseURL = "https://api.spark.io/v1/devices/";
var options = {
    "method": "post",
    "headers": {
        "Authorization": "bearer {8b83c6bddbf8c73f0e835362cff88e90xxxxxxxx}"
    }
};

fucntion on() {
    fetch('https://api.spark.io/v1/devices/53ff6a0666675748243xxxx/on', options)
};

That URL is structured as a GET request, which should actually be a POST request. They need to be treated differently. This guide has been very helpful for this:

1 Like

@Moors7 First off, thank you for taking the time to respond.

SO here is where I am confused. I am trying to make a POST request via the fetch command. I can’t use AJAX where I am trying to implement this. Am i missing something from my code? Do i need to provide a body when using fetch?

This works:

    function on(){

    var POSTurl = baseURL + core1ID + "/onXmasTree";

      		$.ajax({
        		type: "POST",
        		url: POSTurl,
        		data: {
          		access_token: accessToken,
          		args: "pulse"
        		},
	  		});
         }

This Doesn’t work when trying to use the Fetch command:

    var appHeading = "Led Control";
	var core1ID = "53ff6a06666757482xxxxxxxx";
	var accessToken = "8b83c6bddbf8c73f0e835362cff8xxxxxxxxxxxxx";
	var baseURL = "https://api.spark.io/v1/devices/8b83c6bddbf8c73f0e835362cff88e9xxxxxxxxx/onXmasTree";
  var options = {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'bearer {8b83c6bddbf8c73f0e835362cff8xxxxxxxxxxx}'
    }
  };

function on(){
  fetch(baseURL, options)
};

What am i missing here?? I have been at this for days.

@danlee6992

following the code found here: https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/
I tried to control a particle function:

fetch("https://api.particle.io/v1/devices/1e003b0006XXXXXXXXXXXX/setSirenText/", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  body: "/params=toggle&access_token=9bb4daf1ea7a0XXXXXXXXXXXXXXXXX"
}).then(function(res) {
  if (res.ok) {
    alert("Success");
  } else if (res.status == 401) {
    alert("Oops! You are not authorized.");
  }
}, function(e) {
  alert("Error submitting form!");
});

Worked for me (in Firefox browser).

2 Likes

I too struggled with this. I was not able to get the Content-Type: ‘application/json’ POST to work…

I tried the logical approach of using JSON in the ‘body’ key:

// ©2017 w1jp
fetch = require('node-fetch')
const key = {Authorization: 'Bearer xwzzy...............................'} // use YOUR key
const api = 'https://api.particle.io/v1/devices/'
const cmd = '/turnOnOff'
const post = {
	headers: key,
	method: 'POST',
}
// toggle = 1 --> Power On, toggle = 0 --> Power Off
// This does NOT work:
const turnOnOff1 = (device, toggle) => {
	post.headers['Content-Type']='application/json'
	post.body = {arg: toggle.toString()}
	return fetch(api+device+cmd, post).then(j=>j.json()).then(o=>o)
}

And that did not work. So I created another function to test:

// This DOES work:
const turnOnOff2 = (device,toggle) => {
	post.headers['Content-Type']='application/x-www-form-urlencoded'
	post.body = 'arg='+toggle
	return fetch(api+device+cmd, post).then(j=>j.json()).then(o=>o)
}

So I was able to get my code going, but still bothering me why the ‘application/json’ would not work. After a couple hours playing around I tried this to my success:

// Thes DOES work:
const turnOnOff3 = (device, toggle) => {
	post.headers['Content-Type']='application/json'
	post.body = JSON.stringify({arg: toggle.toString()})
	return fetch(api+device+cmd, post).then(j=>j.json()).then(o=>o)
}
1 Like

Thank you so much!