I am triying to make a post query from my React Native (expo) app to Node.js server (express). And the post is doing nothing. Even, console.log doesnot work. Please, need your help with this
React Native App code:
const options = {
method: 'POST',
timeout: 20000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({
a: 10,
b: 20
})
};
fetch(url, options)
.then(response => {
console.log(response.status);
})
.catch(error => console.error('timeout exceeded'));
console.log('3232');
And node.js code:
var express = require('express');
/// create express app
var app = express();
app.use(express.json());
app.post('/g_data/auth', function(req, res){
console.log('LOGGED')
res.send('Hello World!')
});
React Native console return : "3232"
node.js console return nothing
No "new incoming connection detected from …", "LOGGED", as expected.
Please help, what I am doing wrong?
2
Answers
Ok! the final solution is in wrong Headers. For some reasons, React Native app send Headers:
'Content-Type': 'application/json;charset=UTF-8'
But node.js server receives:'Content-Type': 'text/plain;charset=UTF-8'
So, first, I have installed cors to server,
npm i cors -save
and for some reason left Body Parser, and a little bit modernize headers. Here is a final code: React Native App:The server code is:
maybe u need to install and import body-parser on your node js