Express server refusing connection - node.js

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}`);
});

Related

Request urlencoded body is empty in express

I'm trying to get url parameters in express 4.17.3 using the urlencoded middleware but the body is always empty, I reproducted it to a minimal code:
const express = require("express");
(()=>{
const app = express();
app.use(express.urlencoded());
app.get("/", async(req, res)=>{
console.log(req.body); //always print '{}'
res.send();
});
app.listen(83, ()=>{
console.log("test app listening on port 83");
})
})();
Here's my request
http://localhost:83/?param1=42
What am I doing wrong?
A few things to break down. To answer your question to get params you can use
req.query so your code would be:
app.get('/', async (req, res) => {
console.log(req.query)
res.send()
})
Addressing urlencoded it should be changed from:
app.use(express.urlencoded());
to:
app.use(express.urlencoded({ extended: true }))
good habit to not hard code the port so the line of code:
app.listen(83, ()=>{
console.log("test app listening on port 83");
})
should be:
const PORT = process.env.PORT || 83
app.listen(PORT, () => {
console.log(`test app listening on port ${PORT}`)
})
full working code example:
const express = require('express')
const app = express()
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 83
app.get('/', async (req, res) => {
console.log(req.query)
res.send()
})
app.listen(PORT, () => {
console.log(`test app listening on port ${PORT}`)
})
When using express I also like to implement nodemon and if you add this to your package.json:
"dev": "nodemon node index.js"
then in the terminal you can run:
npm run dev
you wont have to restart your server during development changes.

Could not run nodejs on my public ip address

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)

Network error React(frontend) and Nodejs(backend)

I am unable to link my frontend(React) and backend(Nodejs) together with Axios as it keeps encountering Network Error (I have also included CORS into my backend application but it still does not work). The backend runs on Postman too but not when integrated with the frontend. Frontend is running at localhost:3000 while backend runs at localhost:5000
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
Here is what my code looks like:
Frontend:
axios.get("http://localhost:5000")
.then((res) => {
console.log(res.data);
alert("Hi succeedd");
})
.catch((err) => {
console.error(err);
alert("Try again");
});
Backend:
const express = require("express");
const connectDB = require("./config/db");
var cors = require("cors");
const app = express();
app.use(cors({ origin: true, credentials: true }));
//Connect to database
connectDB();
//Init middleware to read data sent in req.body
app.use(express.json({ extended: false }));
app.get("/", (req, res) => res.send("API running"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on ${PORT}`));
have you set up proxy in your package.json correctly?
you should add this line: "proxy": "http://localhost:5000" so that the it knows to proxy requests between a local frontend and backend
see this for more details: https://www.twilio.com/blog/react-app-with-node-js-server-proxy

My lost host server is running in cmd but in browser it is showing localhost didn't send any data

hyper terminal
my local server
code is :
const express = require('express');
const app = express();
const port = 3000;
app.use("/",(request ,res)=> res.end("Hello World"));
app.listen(port , ()=>{
console.log("server is at 3000");
});
Looks like you miss typed res.send
app.use("/", (request ,res) => res.send("Hello World"));

Error while deploying react js and node app to aws

I want to deploy my app to aws, i search and i found alot of tutorials i try each one and i get this error on the browser:
Cannot GET /
I figure maybe that my problem is from my nodeJS server code.
This is my server.js code hope you guys can help me thanks.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const path = require('path');
const cors = require('cors');
//Api routes
const users = require('./routes/api/usuario');
const alumno = require('./routes/api/alumno');
const personal = require('./routes/api/personal');
const zonas = require('./routes/api/zonas');
const sepomex = require('./routes/api/sepomex');
const app = express();
app.use(cors());
//Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//Db config
const db = process.env.NODE_ENV === "production" ? require('./config/keys').mongoURIProd : require('./config/keys').mongoURIDev;
//connect to mongo DB
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
//passport middleware
app.use(passport.initialize());
//passport config
require('./config/passport')(passport);
//Use routes
app.use('/api/usuario', users);
app.use('/api/alumno', alumno);
app.use('/api/personal', personal);
app.use('/api/zonas', zonas);
app.use('/api/sepomex', sepomex);
//serve static assets to production
if (process.env.NODE_ENV === "production") {
//static folder
app.use(express.static("client/build"));
app.get('/*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
I have deployed my app on heroku and works fine.
If you are deploying to EC2 instance then you need to specify IP address in app.listen to be 0.0.0.0, by default it is set to localhost which is not what you want if you want the app to be reachable from outside.
You should change your code to
app.listen(port, '0.0.0.0', () => {
console.log(`Server running on port ${port}`);
});

Resources