Could not run nodejs on my public ip address - node.js

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)

Related

getting CORS error when I try to fetch my api

When I try to fetch my API from my react app, it shows me this error message when my laptop is connected through a LAN connection.
But when my laptop is connected through a mobile hotspot, it doesn't show me any error.
And when I run my API in localhost:5000, it shows me this error message on the terminal.
Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
I already give access to my IP address and it's working fine when I connected through a mobile hotspot.
Why is it happening and how to fix this?
I am able to fetch other APIs but not mine.
API link: https://invoicesapi.herokuapp.com/api/invoices
Github Repo: https://github.com/rishipurwar1/invoice_api
API app.js code:
const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
const connectDB = require('./config/db');
// routes
const invoices = require('./routes/api/invoices');
// Init Middleware
app.use(express.json({ extended: false }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', "*");
res.setHeader('Access-Control-Allow-Methods', "POST,GET,OPTIONS");
res.setHeader('Access-Control-Allow-Headers', "Content-Type, Authorization");
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
// Connect Database
connectDB();
app.get('/api', (req, res) => {
res.render('index')
});
app.use('/api', invoices);
app.listen(port, () => {
console.log('Server is started');
})
You should consider using the cors package (https://www.npmjs.com/package/cors)
npm install cors
Add this to app.js file:
var cors = require('cors')
var corsOptions = {
origin: 'http://yoursite.com',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions))

Receiving the message: Cannot GET / error while using NodeJS and React

I know similar questions have been answered multiple times over the years and I have scoured through just about all of them and can't seem to figure out what my issue is.
I am getting the Cannot GET / error with NodeJS when opening the localhost:5000 in browser. When inspecting I can see it says "Failed to load resource: the server responded with a status of 404 (Not Found)", which I think may be related to my controllers file.
Note: I am trying to code based off of this tutorial: https://www.youtube.com/watch?v=ngc9gnGgUdA
The "This works" message previously showed up for me and the array symbol still shows up. It is the JSX structure part where I first run into this issue (begins at 28:50). I feel I have done exactly as the tutorial explains, but perhaps I need a better person than me to look at it.
server/Index.js
import express from 'express';
// import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
const app = express();
app.use('/posts', postRoutes);
app.use(express.json({ limit: "30mb", extended: true }));
app.use(express.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
const CONNECTION_URL = 'mongodb+srv://*****:******#cluster0.kwo9h.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
const PORT = process.env.PORT || 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server running on port: ${PORT}`)))
.catch((error) => console.log(error.message));
mongoose.set('useFindAndModify', false);
controllers/posts
import PostMessage from '../models/postMessage.js';
// import router from '../routes/posts.js';
export const getPosts = async (req, res) => {
try {
const postMessages = await PostMessage.find();
// console.log(postMessages);
res.status(200).json(postMessages);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
export const createPost = async (req, res) => {
const
post = req.body;
const newPost = new PostMessage(post);
try {
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
res.status(409).json({ message: error.message });
}
}
routes/posts
import express from 'express';
import { getPosts, createPost } from '../controllers/posts.js'
const router = express.Router();
// localhost:5000/posts
router.get('/', getPosts);
router.post('/', createPost);
export default router;
Any help would definitely make my day. Thank you!
In the tutorial, there are actually 2 applications. The first one is the backend (NodeJS), which is running on port 5000. The second one is the frontend (React), which is running on port 3000.
At 30:50, you see that the mentor typing "npm run start" on the 2nd terminal to start the react application.
At 33:12, the URL is localhost:3000, which is pointing to React application. It isn't localhost:5000. You get the error 404 because in the NodeJS part, there is no GET "/" route. So you just need to use the correct URL.
You cannot directly use router.
declare the express app first and attach the router to it.
const app = express();
const router = express.Router();
router.get('/', getPosts);
router.post('/', createPost);
app.use('/', router)
export default router;
You have no route declared for http://localhost:5000 - your router is under /posts
So you need to visit http://localhost:5000/posts to see something.
If you want something to appear directly at http://localhost:5000 you can do something like
index.js
const app = express();
app.use('/', (req, res) => {
res.send('works')
})
app.use('/posts', postRoutes);
What do you want to see at http://localhost:5000?
If you want to display a index.html website you can put your index.html file in a a folder e.g. public and add
app.use(express.static('public'))
If you want your posts to appear at http://localhost:5000 then change your routing
index.js
const app = express();
app.use('/', postRoutes)

Express server refusing connection

I was just starting to build a server with Express, learning the workflow, and it worked just fine, then, at one point, my connection started being refused by the server. I cannot connect, nor can I send any other request to the server to check if it's alive (it happened after sending a POST request through Postman).
I made a simple POST request which would just return JSON data that was sent and after I tried it, it just shut down. I tried restarting my internet, pc and server.
I'm connecting to http://localhost:5000, the message I get is "This site can't be reached -- localhost refused to connect.".
My server says it's running and listening on port 5000 yet it doesn't let me connect.
I'll put my code right below this so you can tell me what could be wrong.
import express from 'express'
import mongoose from 'mongoose'
import cors from 'cors'
import userRoutes from './routes/userRoutes.js'
const app = express()
const PORT = process.env.PORT || 5000
const mongooseConnectionUrl= "url"
app.use(cors());
app.use(express.json)
app.use("/users", userRoutes);
mongoose.connect(mongooseConnectionUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
})
app.listen(PORT,() => {
console.log(`Server running on port: ${PORT}`)
})
app.get('/', (req, res) => {
res.send("<h1>Hello World</h1>")
})
The problematic line is: app.use(express.json); -> app.use(express.json());
I'm using require() in my example solution but it does not really matter. Also I did not include your mongoose related code.
const express = require("express");
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json());
app.get("/", (req, res) => {
res.send("<h1>Hello World</h1>");
});
app.use("/users", (req, res) => {
res.json({ hello: "world" });
});
app.listen(PORT, () => {
console.log(`Server running on port: ${PORT}`);
});

Angular 7 Service Worker not Working Offline when using Node.Js Server

I have an Angular 7 project with PWA functionality added.
I basically have all PWA-related settings set to default.
My issue is, that offline mode does not work when deploying the project to my server. It's also not working when starting the server on localhost.
However, when using the npm module http-server to host the app on localhost, the offline mode works.
Online the service worker is applied:
Here is what happens when loading app offline:
The code of my Node.Js server looks like this:
require('module-alias/register')
const express = require('express')
const app = express()
const prod = require('#root/prod')
const port = process.env.PORT || 3000
const path = require('path')
const compression = require('compression')
app.use(compression())
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(path.join(__dirname, '../client/dist/client')));
const api = require('#root/api/api.routes')
app.use('/api', api)
app.get('*', (req, res) => {
res.status(200).sendFile(path.join(__dirname, '../client/dist/client/index.html'))
})
app.use(function (err, req, res, next) {
console.log('error occured', err.stack);
res.status(500).send({ "Error": err.stack });
});
app.listen(port, () => {
console.log(`• • •`)
console.log(`• Server launched 🚀 on port`, port)
console.log(`• Server running in ${prod ? '🔥 production' : '💉 development'} mode`)
console.log(`• • •`)
})
Here are all files from the production build:

Rest Api with node.js localhost not answering

Hy there, I'm trying to learn to make a REST API. I have the following code, where I mention that i have no error. When I try to access localhost:3000 nothing happens it's just reloading a blank page. What am I doing wrong?
Servers.js
const http = require('http');
const app = require('./app').default;
const port = process.env.port || 3000;
const server = http.createServer();
server.listen(port);
App.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.status(200).json({
message: 'It works!'
});
});
module.exports = app;
You've not defined any route. Express generator generates the boilerplate code which is use full to start with.
You can also define a route like this:
app.use('/', function (req, res, next) {
return res.render('index', {title: 'DASHBOARD', 'data': ''});
});
Have a look at this doc: https://expressjs.com/en/starter/generator.html

Resources