Last active
October 3, 2018 23:07
-
-
Save lopugit/b5593b5e0eb4d7963a32b525b96ee631 to your computer and use it in GitHub Desktop.
Isomorphic Fetch post body data empty solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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