Network error React(frontend) and Nodejs(backend) - node.js

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

Related

find the error while deploying the node.js app to server

I found the error while deploying the node app on the server. the index.js file code
const connectToDb = require("./DBconfig");
const express = require('express')
const router = express.Router();
var cors = require('cors');
connectToDb();
const app = express();
const port = process.env.PORT | 5000;
app.use(cors());
app.use(express.json());
connectToDb();
app.use( '/api/user' ,require('./routes/user') );
app.use( '/api/post' ,require('./routes/post') );
app.get('/', (req, res) => {
res.send('The site is start now')
})
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
const path = require("path");
app.get("*",(req,res)=>{
res.sendFile(path.resolve(__dirname,'client','build','index.html'))
})
}
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
when I deploy the app and install the node in the server like how I install the node in server I attached the picture in which I show the installation of the node. and above I add the index.js code. It works properly in the local machine but if I hit the URL of backend backendURL it show the service unavailable error message kindly give me the solution to solve this problem.

Node app is not reachable on EC2 insrance

I have deployed simple nodejs application on EC2 instance and modified all inbound rules to made port publicly accessible but even after that I am unable to access application.
below is my app:
server.js
const express = require('express');
const log = require('./logger');
const app = express();
app.get('/',(req,res) => {
res.send("Happy logger");
});
app.listen(2000,() => console.log("App is listening"));
Below is my inbound rules settings
When I am hitting on ec2-3-82-196-99.compute-1.amazonaws.com:2000 url its showing below error.
Someone let me know what I am doing wrong.
From your screenshot, you are accessing HTTPS in Chrome:
https://ec2-3-82-196-99.compute-1.amazonaws.com:2000.
As the commenter suggested, should use HTTP instead (make sure you see the 'Not secure' sign):
http://ec2-3-82-196-99.compute-1.amazonaws.com:2000
I am also having the same problem here.
I tried both HTTP and HTTPS, but no use. The app is working in the localhost (A windows 2022 server).
URLS:
https://ec2-3-110-102-41.ap-south-1.compute.amazonaws.com:8080
http://ec2-3-110-102-41.ap-south-1.compute.amazonaws.com:8080
Security Inbound Rules:
Inbound Rules
NodeJS Code:
const express = require("express");
const cors = require("cors");
const dotenv = require('dotenv')
dotenv.config();
const app = express();
app.use(cors({
origin: "*"
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.json({ message: "Hello" });
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, '0.0.0.0', () => {
console.log("Server listening on port::::::::::::::::::::::\n", PORT);
});

"POST http://localhost:5000 net err failed"

I'm trying to send a post request to a node server using axios, here's what I've done in react-js.
axios.post('http://localhost:5000', {
firstName: 'Finn',
lastName: 'Williams'
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
And here's what I've done in the server.
const express = require('express')
const app = express()
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Every time I send the request, I get the following message in the console Access to XMLHttpRequest at 'http://localhost:5000/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What should I do to fix that?
Install CORS npm package to configure your express HTTP server cors.
npm install cors
Then import CORS package in your express application file like that:
const express = require('express')
const cors = require('cors')
app.use(cors())
const app = express()
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Then in your request code, you should to request with GET method. You are using axios.post() which does POST request. And that will response you with 404 because you don't have app.post('/') route handler in your application. So the code should look like this:
const express = require('express')
const cors = require('cors')
app.use(cors())
const app = express()
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/', (req, res) => {
res.send(Hello ${req.body.firstName} ${req.body.lastName}!`)`;
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
You can install the cors
npm install cors --save
after that you can add this code on server file
var cors = require('cors')
app.use(cors()) // Use this after the variable declaration
You're not sending CORS headers on your responses, so the requests are denied. This can be easily solved by:
Run npm i cors
Change your code to
const express = require('express')
const cors = require('cors');
const app = express()
const port = 5000;
app.use(cors());
// all the other stuff
This error basically occurs because of a security mechanism that browsers implement called the same-origin policy. It prevents any cross-domain communication which may lead to cyber attacks like cross-site request forgery.
While we develop backend APIs for our frontend apps, we have to enable Cross-Origin Resource Sharing (CORS) in our backend server. To do that there are several libraries, the most common one is Cors package. Install it and use it in your server app as follows-
const express = require('express');
const app = express();
const port = 5000;
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World!')
})

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

CORS POST request blocked in EXPRESS & REACT on hosting & domain

I'm using express CORS module & react AXIOS on my host & domain.
I defined CORS() in my route middleware, and the GET request worked perfectly.
but for POST & PUT requests still, the Access-Control-Allow-Origin BLOCKED error displays.
ALSO I'm using webpack and dev server to proxy front end react
This is my express server.js file
const express = require("express");
const app = express();
const db = require("./config/db");
db.connect(() => {
console.log(`Postgres connected`);
});
// Middlewares
// CORS
const cors = require("cors");
app.use(cors(
{
origin: http://asia-sarmaye.ir
}));
// BodyParsing
var bodyParser = require("body-parser");
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// Router
app.use("/api", cors(), require("./routes/dum"));
// Listening
const port = 4000;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
And this is REACT axios POST request
axios
.post(
"http://api.asia-sarmaye.ir/api/user",
{
headers: { "Access-Control-Allow-Origin": "*" }
},
data,
res => {
console.log(res.data);
}
)
any idea how to fix this?
You need to set proxy.
Hope below given link help you. It helped me too.
Enable CORS in my React App with Node.js backend

Resources