Hi guys i have a basic code of nodejs like
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
var createError = require("http-errors");
require("dotenv").config();
const app = express();
//ROUTES//
const userRoutes = require("./routes/UserRoutes");
app.use(cors());
app.use(bodyParser.json());
app.use("/", (req, res, next) => res.send("hello"));
app.use("/api", userRoutes);
mongoose
.connect(process.env.MONGOURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("connected and running"));
app.use((req, res, next) => {
next(createError(404, "Not found"));
});
app.use((err, req, res, next) => {
console.log("in error middleware");
res.status(err.status || 500);
res.send({
status: err.status || 500,
message: err.message,
});
});
app.listen(4000,() =>
console.log(`listening on 4000`)
);
So as of now i am running on port=4000 so can access it via
http://localhost:4000
but i plan to use this server for my react native app using expo client app by which i am running my app on my mobile phone I see that i cant get access via localhost so in client side i tried to access it via
http://<my-public-ip>:4000
but it doesn't get any response back only
http://127.0.0.1:4000/
but this works only in my pc and it's obvious, how do i access the local server through my mobile which is running my app?
You want to acces it from your local home network or from the internet?
If it's from local network, juste use the local ip address of your pc (it probably starts with 192.168.XX.XX), you can find it with ipconfig
on Windows CMD or ip addr
on a Linux shell.
If it's from WAN (internet) you need to configure port forwarding in the firwall of your router, this mean "translate <my-public-ip>:4000
into <local-pc-ip>:4000
(found just like before)". (You can find infos on the web by searching you the type/brand of your router to do it)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.