# Javascript Fetch API

**URL:** <https://community.particle.io/t/javascript-fetch-api/22705>\
**Category:** Troubleshooting\
**Created:** [May 6, 2016, 2:45am UTC](https://community.particle.io/t/javascript-fetch-api/22705 "2016-05-06T02:45:36Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![marmageek](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/marmageek/32/27325_2.png) [@marmageek](https://community.particle.io/u/marmageek)\
**Post date:** [October 29, 2017, 2:29pm UTC](https://community.particle.io/t/javascript-fetch-api/22705/7 "2017-10-29T14:29:40Z")

</div>

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)
}
```

---

_[View the full topic](https://community.particle.io/t/javascript-fetch-api/22705)._
