How to Connect to localhost Mongodb using an emulator? - mongodb

First time making a question here so sorry for anything that isn't clear.
Basically I took a react course that set up a functional site with crud and now I'm trying to set up something similar in react native. So I'm new to react, react-native, and mongodb; basically everything I'm working with. This is for self study as well, so just trying to expand my skills.
This is the code that works in my react app under server.js from the backend
const client = await MongoClient.connect("mongodb://localhost:27017", {
useUnifiedTopology: true,
});
//api inbetween these two
app.listen(8000, () => console.log("Listening on port 8000"));
On my front end in my package.json I have this
"proxy": "http://localhost:8000/",
from my understanding this basically lets my frontend "proxy"/mask itself as if its coming from port 8000. Then I can call it using a url like below.
useEffect(() => {
const fetchData = async () => {
const result = await fetch(`/api/articles/${name}`);
const body = await result.json();
setArticleInfo(body);
};
fetchData();
}, [name]);
In my react-native app I get an unhandled promise rejection and in postman I get an internal 500 error with no associated error seems to be null since nothing is printed. Doing some research, I think the issue is because now I'm running this app on an emulator so I think it can't identify the main computer or localhost?
I've tried changing the localhost part of the address to my ipv4 address, to the expo connection url, 0.0.0.0, and also to what I believe is the android localhost 10.0.2.2 but none of them seems to work. example of android localhost change.
server.js
const client = await MongoClient.connect("mongodb://10.0.2.2:27017", {
useUnifiedTopology: true,
});
//api inbetween these two
app.listen(8000, () => console.log("Listening on port 8000"));
package.json
"proxy": "http://10.0.2.2:8000/",
When it's set to 10.0.2.2 postman times out and the app still has the unhandled promise error.
When it's set to 0.0.0.0 postman returns a 500 error with no details and the app still has the unhandled promise error.
When it's set to the expo url it straight up doesn't work.
When its set to my ipv4 address I get the unhandled promise and postman returns this error
"error": {
"name": "MongoServerSelectionError",
"reason": {
"type": "Single",
"setName": null,
"maxSetVersion": null,
"maxElectionId": null,
"servers": {},
"stale": false,
"compatible": true,
"compatibilityError": null,
"logicalSessionTimeoutMinutes": null,
"heartbeatFrequencyMS": 10000,
"localThresholdMS": 15,
"commonWireVersion": null
}
}
Posts I've looked at
Connect to MongoDB Atlas Cluster db with react-native app
Mongodb connection with react native form
React Native / Expo : Fetch throws “Network request failed”
why do we use 10.0.2.2 to connect to local web server instead of using computer ip address in android client

Your useEffect is wriiten wrong
Write it like this
useEffect(() => {
GetArticles(); // Called whenever there's a change in name
}, [name]);
// Create this function outside useEffect
const GetArticles = async () => {
try {
// Also in your fetch you have yo write url like this
const result = await fetch(
`http://${YOUR_IPv4_ADDRESS}:8000/api/articles/${name}`
);
const body = await result.json();
setArticleInfo(body);
} catch (error) {
console.log(error);
}
};
Also this is 100% correct
const client = await MongoClient.connect("mongodb://localhost:27017", {
useUnifiedTopology: true,
});
//api inbetween these two
app.listen(8000, () => console.log("Listening on port 8000"));
Don't change it to this
const client = await MongoClient.connect("mongodb://10.0.2.2:27017", {
useUnifiedTopology: true,
});
//api inbetween these two
app.listen(8000, () => console.log("Listening on port 8000"));

Related

Can Bunjs be used as a backend server?

Now we can start a react App with bun as a server
Can we use Bunjs as complete backend server?
For Example, Can bun run this code?
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('hello world')
})
app.listen(3000)
I guess Bun does not YET implement all node.js api's. I tried http and it seems currently missing. And as much I understand it currently has its own built-in HTTP server.
Check the "Getting started" section on -> https://bun.sh/
A sample server:
export default {
port: 3000,
fetch(request) {
return new Response("Welcome to Bun!");
},
};
(This example reminds me of serverless functions.)
As this is the case, it seems you can not rely on Node.js http, or most probably any server framework like express.
At least for now, bun's roadmap (https://github.com/oven-sh/bun/issues/159) shows a line, which I am not sure is talking about node's http server or sth. else about Bun's own server.
Once complete, the next step is integration with the HTTP server and
other Bun APIs
Bun api is really different from nodejs, I created a library called bunrest, a express like api, so new user does not need to learn much about bun.
Here is how to use it
Install the package from npm
npm i bunrest
To create a server
const App = require('bunrest');
const server = new App.BunServer();
After that, you can call it like on express
server.get('/test', (req, res) => {
res.status(200).json({ message: 'succeed' });
});
server.put('/test', (req, res) => {
res.status(200).json({ message: 'succeed' });
});
server.post('/test', (req, res) => {
res.status(200).json({ message: 'succeed' });
});
To start the server
server.listen(3000, () => {
console.log('App is listening on port 3000');
});
Other way is using Hono: https://honojs.dev/
There is a working demo: https://github.com/cachac/bun-api
Import package and set new instance
import { Hono } from 'hono'
const app = new Hono()
Create routes:
Instead of NodeJs res.send(), use c.json({})
app.get('/hello', c => c.json({ message: 'Hello World' }))
export and run api server:
export default {
fetch: app.fetch,
port: 3000
}

MongooseServerSelectionError: In Cpanel , Simple Routes are working But whenever try to Hit route of (MongoDb get/set) its Not Working. Mongodb error

Hy I have React NodeJs App, Trying to Deploy it On Cpanel Namecheap...
The site is Deploy Correctly. And Simple Routes are also Working but Routes that use to get/set data from DB is Note Working and stay in a loading state for long time...
I Also See my stderr.log file it says "MongooseServerSelectionError"...
But my MongoDB NetworkAccess is a enter image description herepublic already!!!!
Please Help..
here is my connection Code start.....
const mongoose = require("mongoose");
const connectDb = async () => {
mongoose.connect(
"mongodb://serverBoiler:myPassword#cluster0-shard-00-00.t30x6.mongodb.net:27017,cluster0-shard-00-01.t30x6.mongodb.net:27017,cluster0-shard-00-02.t30x6.mongodb.net:27017/RagdollCatServer?ssl=true&replicaSet=atlas-1r1rhb-shard-0&authSource=admin&retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
}
)
.then((res) => console.log(`Db connected on ${res.connection.user}`));
};
module.exports = connectDb;
////////////////////////////////////////////////////////////////////////
You better try with localhost like this
it may help full I think.
var db="mongodb://localhost/loginapp"
mongoose.connect(db,{useNewUrlParser: true})
.then(()=>console.log('MongoDB successfully connected'))
.catch(err=>console.log(err));

How to connect my app to SocketIO server if i have CORS enabled

I'm trying to connect my Flutter APP to my SocketIO server (v2), if I enable cors
const io = require("socket.io")(httpServer, {
origins: ["http://localhost:5500", "*", "*:*"]
})
It shows this error (on Android Studio)
I/flutter (20998): reconnect_error: WebSocketException: Connection to 'http://192.168.1.8:3000/socket.io/?EIO=3&transport=websocket#' was not upgraded to websocket
If I disable cors it works perfectly, but I need cors because I need to be able to connect my test file (chat.html) that runs on localhost:5500, and in the future, connect my Flutter Web App
const io = require("socket.io")(httpServer, {
allowRequest: (req, callback) => {
const origin = req.headers.origin
const origins = [
undefined,
"http://localhost:5500",
"http://127.0.0.1:5500"
]
callback(null, origins.includes(origin))
}
})
(This works only for v2)

I'm getting a Web Push Error Code Status 403, which is driving me nuts, because its telling me to use firebase. What's going on?

I keep getting a WebPush Error (Status Code 403) fro Chrome for a PWA I'm building and the body says that I need to use the VAPID server key from the 'firebase console' but I used nodes Web-Push library to generate the VAPID Keys, whats going on? Do I have to use firebase to build PWAs in Chrome?
Here's the Error Message I'm getting from the browser when I send a push notification:
name: 'WebPushError',
message: 'Received unexpected response code',
statusCode: 403,
headers:
{ 'content-type': 'text/plain; charset=utf-8',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '0',
date: 'Thu, 31 Oct 2019 19:59:02 GMT',
'content-length': '194',
'alt-svc':
'quic=":443"; ma=2592000; v="46,43",h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000',
connection: 'close' },
body:
'the key in the authorization header does not correspond to the sender ID used to subscribe this user. Please ensure
you are using the correct sender ID and server Key from the Firebase console.\n',
endpoint:
'https://fcm.googleapis.com/fcm/send/exXmW3OFOTY:APA91bEKW_vxnvOZohog34pprDH6XvBsxtfnUpBdYY7z_7q4GZGa4wrmtBBg4kTRwLtgy3lNpCs8SMlvOr4nY-Fu_4zUus6zEJh69581Ier14QZxkEEVXyZHKRaZcmHa3zmbZRB4VD7Z
and here's the code that is running my node server:
//Handle imports
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const webPush = require('web-push')
const vapidKeys = require('./vapid.json')
const path = require('path')
//Setup application
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.use('/static', express.static(path.join(__dirname,'frontend')))
const port = 8080
//Set up webpush
webPush.setVapidDetails(
'mailto: <email>',
vapidKeys.publicKey,
vapidKeys.privateKey
)
const pushOptions = {
proxy: '<proxy>'
}
//setup Push Notification
const sendNotification = (subscription, dataToSend='') => {
webPush.sendNotification(subscription, dataToSend, pushOptions).catch(error => { console.log('Damn it: ', error.message, '||', error)
})
}
//Server Routes Defined
app.get('/', (req, res) => res.sendFile('index.html', { root: './' }))
//Setup Database Methods
const dummyDb = {subscription: null}
const saveToDatabase = async subscription => {
dummyDb.subscription = subscription
}
//Other Server Routes
app.post('/save-subscription', async (req, res) => {
const subscription = req.body
await saveToDatabase(subscription)
console.log('subscribed!')
res.json({message: 'success'})
})
app.get('/send-notification', (req, res) => {
const subscription = dummyDb.subscription
const message = 'hello world'
sendNotification(subscription, message)
res.json({message: dummyDb.subscription})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
I have node.js express, postgres, angular 8 app.
I had the same problem and I got it working by adding the "gcm_sender_id": in the manifest.webmanifest file (or manifest.json I also used firebase generated public and private keys.
your gcm_sender_id is your project id in google cloud or firebase sender id
Same situation and almost lost my sanity. I tried inserting gcm_sender_id with a Firebase senderId and worked finally. I didn't have a Firebase account, but I was able to create a project in seconds and my senderId was ready to be used in the messaging settings.
But a caveat: After my modification in the manifest.json (in my case) in the root's folder, it was needed to uninstall the current service worker and restart my React project. Then I followed again all steps back by asking permissions and subscribe the user and finally trigger a push notification.
During my heat researches for a solution, I found that gcm_sender_id is also used to send and validate push messages from other browsers. According to Google Web Updates:
For Chrome prior to version 52, Opera Android and the Samsung Browser,
you're also still required to include a 'gcm_sender_id' in your web
app's manifest.json. The API key and sender ID are used to check
whether the server making the requests is actually allowed to send
messages to the receiving user.

Socket working only with debug mode react native

My socket emit works properly only on debug mode, when i tried with release APK nothing happened.
Code to connect socket -
socket = io(SOCKET_URL, {
transports: ['websocket'],// you need to explicitly tell it to use websockets
forceNew: true,
jsonp: false
});
socket.on('connect', () => {
console.log('connected!');
});
socket.on('disconnect', () => {
console.log('disconnect!');
});
Code to emit event
socket.emit('LIVE_MSG', { msg: "asdfasasdf3" }, (res) => {
console.log(res);
})
I have tried many options with socket connection i.e. timeout, setting and removing jsonp
Also tried with window.navigator.userAgent = "react-native";
But the result is none, socket only emits event when it is in debug mode, gone mad why it is not working with release apk.
Please help.
If you don't specify url, socket set url as localhost.
https://socket.io/get-started/chat/
"Notice that I’m not specifying any URL when I call io(), since it defaults to trying to connect to the host that serves the page."
(I'm not familiar with socet.io.)