Skip to content

Instantly share code, notes, and snippets.

@lopugit
Last active October 3, 2018 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lopugit/b5593b5e0eb4d7963a32b525b96ee631 to your computer and use it in GitHub Desktop.
Save lopugit/b5593b5e0eb4d7963a32b525b96ee631 to your computer and use it in GitHub Desktop.
Isomorphic Fetch post body data empty solution
Client:
fetching with headers:
{ "Content-Type": "application/json" }
Stringifying JSON:
body: JSON.stringify(data)
Server: add:
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(require("body-parser").json())
app.use(bodyParser.urlencoded({ extended: true }));
Eg.
Client:
let data = { something: 'something else' }
fetch(`/api/register`, {
method: 'POST',
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" }
})
.then((res) => {
res.json().then(res=>{
console.log('res', res)
})
})
.catch(err=>{
console.error('err', err)
})
Bonus tidbit:
To return/res json you need to set this header:
router.post('/register', async (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.json({etc: 'etc...'})
// etc....
})
And fetch requires res.json().then(res=>{}) format for some dumb af reason
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment