I Cannot Connect my Expo App to localhost Api - javascript

I am building a react native app using expo and I am trying to connect to a http://localhost/api running on my localhost. All I ma getting is network error.
The expo app is running on a real device. I did that using expo start --localhost --android
I have tried using the ip address provided by the ipconfig /all instead of localhost but I am still getting Network Error
Here is my code
const fetchApi = async () => {
try {
const res = await axios.get("http://10.2.0.56:8000/");
console.log(res.data);
} catch (error) {
console.log(error.message);
}
};
Somebody please help

Related

React Native Firebase problem with emulator on physical device

I am programming an app with React Native. To use Firebase in this app, I installed the React Native Firebase npm package. I have set up everything to make requests to Firebase functions and this works smoothly. I am currently trying to set up the Firebase functions emulator to make my dev journey easier. But I can't seem to connect to the emulator.
Client
import functions from '#react-native-firebase/functions';
const DEV = true
if (DEV) {
functions().useEmulator("192.168.x.x", 5001);
}
const sayHelloWorld = () =>{
functions()
.httpsCallable('helloWorld')()
.then(response => {
console.log(response.data)
});
}
sayHelloWorld()
Backend Function
exports.helloWorld = functions.https.onRequest((request, response) => {
response.status(200).send({"data":"Say hello world"});
});
I am using the useEmulator function to switch to the emulator running on port 5001. I am not using useFunctionEmulator as shown in the documentation (https://rnfirebase.io/functions/usage) because it appears to be outdated, but I tried it, and it doesn't work as well. I am using my local IP address for the host because I am running a physical android device. I have no issue running the app, but as soon as I execute the function request nothing happens and after one minute I get the following error message:
Possible Unhandled Promise Rejection (id: 0):
Error: DEADLINE_EXCEEDED
Error: DEADLINE_EXCEEDED
callFirebaseFunctions#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:116187:60
_performTransitionSideEffects#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:65273:22
_receiveSignal#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:65215:45
onResponderRelease#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:65055:34
invokeGuardedCallbackProd#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:3940:21
invokeGuardedCallback#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4044:42
invokeGuardedCallbackAndCatchFirstError#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4048:36
executeDispatch#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4124:48
executeDispatchesInOrder#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4144:26
executeDispatchesAndRelease#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:5493:35
forEach#[native code]
The emulator logs do not show any activity.

react native firebase authentication emulator error message thrown : Error: A network error

I am attempting to use the recently released firebase emulator suite. specifically the authentication emulator.
I have the emulator installed and have created an test user in the auth emulator. as follows:
Within my code I have:
if (firebase.apps.length === 0) {
console.log("setup.js: initializing firebase....")
firebase.initializeApp(firebaseConfig);
firebase.auth().useEmulator('http://localhost:9099/');
} else {
firebase.app(); // if already initialized, use that one
}
to utilized the emulator for authentication. alas I get the following network error:
Has anyone had success utilizing the firebase emulator suite with react native?

React API communication refuse on cloud IDE (MERN Stack)

I'm learning MERN stack following the below tutorial.
https://medium.com/#beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1
I've decided to use a cloud platform IDE called goorm IDE (https://ide.goorm.io) which is similar to cloud 9 IDE, and as I followed the tutorial, I realized a simple problem, that the testing environment is little different because I can not access the localhost on my machine (Or at least I don't know how to.)
Working on the back End did not have much problem because this IDE provides a domain where I can access and I could just run the server.js (not the whole react app) and test the API end point easily.
But now that I run the whole react app as I'm learning Front End side, I discovered that my server.js is not accessible as before when I was running just the server and I would get refused from the connection as below.
Below code is the actual code I'm using from the front End side in order to make API call to the server.
axios.post('http://localhost:5000/users/add', user).then(res => console.log(res.data));
// I tried changing the url to external domain.. changing the directory.. with no luck..
And below is the code for server.js file.
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("Mongo DB database connection established successfully");
});
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, process.env.IP, () => {
console.log(`Server is running on port: ${port}`);
});
And below is the url of the page where I'm actually trying to make the API Call.
https://zimen.run.goorm.io/user
Other environment information
Running URL and Port setting from the IDE : https://zimen.run.goorm.io:3000
React App directory : root/mern-exercise-tracker/
dependencies : express, create-react-app, mongoose, cors
I'm wondering if it would be better to start the whole project again in a clean local environment..
If someone could please help, it would be much appreciated.
Any other information needed, please let me know, or you can actually join the IDE online as this is a cloud IDE.
Thank you in advance.
== UPDATE ==
Sorry I've forgotten to attach the error log.
xhr.js:178 POST https://localhost:3000/users/add net::ERR_CONNECTION_REFUSED
Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
its seems you have CORS error,i solved this problem by installing CORS extension on Goolge Chrome
Set PORT=5000 in Nodejs server-side and the default port for React frontend as PORT=3000.
Set your own separate custom 'Running URL and Port' for Nodejs and React.
Example:
https://[custom-client-side-name].goorm.io
for React at PORT=3000
and
https://[custom-server-side-name].goorm.io
for Nodejs at PORT=5000
For Axios command on React side, use:
axios.post('https://my-server-side.goorm.io/users/add', user).then(res => console.log(res.data));
and similarly, the React frontend can be found on your custom website you have set up: https://my-client-side.goorm.io/[custom-routes]

Firebase Cloud Messaging - getToken() error in JS SDK

I am developing an app for KaiOS, a fork of the old Firefox OS, for which apps are based on HTML5 + JS. When compiling and running on device, Firebase Cloud Messaging stops working. I receive an error as follows.
TypeError: 'applicationServerKey' member of
PushSubscriptionOptionsInit could not be converted to any of:
ArrayBufferView, ArrayBuffer.
I've followed the instructions in the Firebase docs here as well as this tutorial on setting up FCM for Progressive Web Apps here. I can confirm I am setting my key before calling getToken, as shown below:
import firebase from "firebase";
const messaging = firebase.messaging();
messaging.usePublicVapidKey("<my-key-from-firebase-settings>");
messaging.getToken().then((currentToken) => {
...
}).catch((err) => {
...
});
I have searched for the above error, but to no avail. Does anyone know what this error means or how to fix it? Running the application in the browser on my development machine, everything works perfectly.
Note: the app is written in Typescript
Firebase SDK Version: 7.12.0
It might not be of help to you but I recently experienced a similar error message in a different environment:
Error: Failed to execute 'subscribe' on 'PushManager': The provided
value is not of type '(ArrayBuffer or ArrayBufferView)'
It was fixed in version 7.13.2 of Firebase:
https://github.com/firebase/firebase-js-sdk/issues/2712
https://firebase.google.com/support/release-notes/js#version_7132_-_april_2_2020

How would one resolve a 'UnhandledPromiseRejectionWarning' error, while trying to deploy a node.js app?

I am currently working on a project in which I am using a js library called 'jsPsych' to conduct an experiment. I am using node.js, in combination with heroku to host and deploy my app online, with Mongo Atlas as my database. While writing the node.js script for connecting to Mongodb, I used the tutorial provided here https://www.mongodb.com/blog/post/quick-start-nodejs-mongodb--how-to-get-connected-to-your-database. Now everything works fine in a local environment, but as soon as i deploy my experiment online, I get the message: "The experiment failed to load." Upon checking the heroku logs, I saw this:"(node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()."
This is the node.js script for connecting to mongodb:
const {MongoClient} = require('mongodb');
async function main(){
const uri = "mongodb+srv://username:password#cluster-url/test?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try{
await client.connect();
await listDatabases(client);
} catch (e) {
console.error(e);
}
finally {
await client.close();
}
}
main().catch(console.error);
async function listDatabases(client){
databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};
Since I am a novice at coding, and this is my first experience with back-end code, I am struggling to find a solution to this problem. Also,it seems like the script already has a .catch function included, does this mean that I am not handling a promise using a .catch function? Could this be what's causing my problem?
Are you using an free cluster on mongoDB?
Then you should probably log in into your account, go to network access and add your server IP Adress.
I guess you didnt opened your server IP for your cluster
The solution that worked for me was to set the IP address to 0.0.0.0/0 at the Mongodb Atlas "Network Access' page.

Categories