Javascript Fetch API

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