Reputation: 1339
I'm using NodeJS for the backend, and ReactJS for the frontend.
I've a problem with request Axios network. All my Get request work. But Post request don't work. I have just this error "network error"
I created a simple webservice to show you my problem :
//Serveur code
helloWs : (request:Express.Request, response:Express.Response) => {
try {
response.send('hello WS !')
} catch (error) {
console.error(error)
response.send('error' + error + 'status : ' + error.response.status)
response.end()
}
}
//Here I create my root
router.post('/helloWs',DocumentController.helloWs)
//This is my front
axios.post('http://localhost:9000/1/documents/helloWs', {
}) .catch(function (error) {
if (error.response) {
console.log('Error data : ', error.response.data);
console.log('Error status : ', error.response.status);
console.log('Error headers : ', error.response.headers);
} else if (error.request) {
console.log('Error request : ', error.request);
} else {
console.log('Error message : ', error.message);
}
console.log(error.config);
})
In the navigator console, I've just network error
, and my webservice is in OPTION and not in "POST"
I'm trying to add header in axios, but it doesn't work. I specify that I've tested with postman, and it's okay. Do you have an idea ? Thank you
Upvotes: 8
Views: 41153
Reputation: 11
If you run your react-native app on an android emulator, this might work:
Run this in powershell or cmd: adb reverse tcp:9000 tcp:9000
This will make your android emulator reach localhost at port 9000.
Upvotes: 1
Reputation: 111
I found this bug occurring with my setup. For some reason, prepending the POST request with http:// (this is a dev server on localhost) enabled the network once again.
I haven't dug into the axios docs, but I am guessing there is some code that automatically prepends GET requests with http:// but fails to do so for POST methods? That's one possibility to explain this odd behavior.
Upvotes: 1
Reputation: 8632
It is most likely a cors related error, the OPTION request is made by the browser before the actual request to check if your domain has the rights to access the resource.
Postman doesn't do the preflight request that's why you get the response
try adding this middleware in your server side code before defining the routes
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Upvotes: 16
Reputation: 121
I had a similar error that was near-impossible to debug. It ended up being that my backend wasn't https whereas my frontend was. Fixed it by making my backend https and I no longer get the error!
Upvotes: 0