I am trying to perform HTTP requests from an Expo (React-Native) application to a node.js server running on my PC however I am having some trouble getting this working. I am using ngrok to expose the localhost and am using the ngrok server in the fetch but I continue to get a Network request failed upon my POST request.
I am creating my server as follows:
app.listen(process.env.PORT, () => {
console.log(`Application is listening on ${process.env.PORT}`);
(async function () {
const endpoint = await ngrok.connect(process.env.PORT);
console.log(
`Publicly accessible tunnel to localhost:${process.env.PORT} is available on ${endpoint}`
);
})();
});
where process.env.PORT is set to 3000. When i start my server up, it successfully connects and I am able to send HTTP requests through Postman and successfully see the data being injected to my mongoDB database.
Now, for my frontend fetch, I have the following code:
try {
let response = await fetch(`https://0b02aa4f40e2.ngrok.io/signup`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
}),
})
.then((response) => response.json())
.then((state) => this.setState(state));
console.log(response);
} catch (err) {
console.log("Fetch didnt work.");
console.log(err);
}
where the fetch url is the url provided by ngrok upon server startup. Im just doing some basic post configuration and passing along some email/password i am inputting through the app. However, fetch always fails and i end up with the same error as follows:
Network request failed
- node_modules\whatwg-fetch\dist\fetch.umd.js:487:17 in setTimeout$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:135:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:387:16 in callTimers
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425:19 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
I am at a loss as to what im doing wrong here or what im missing.
I am using my iPhone to test. I have the android simulator setup but haven't tried it yet figuring it would yield the same result.
I had the metro bundler connection mode set to LAN and I had to change it to tunnel and now it works when I provide it the ngrok URL and am able to send post requests.