Calls to local host not working with ReactJS/Axios/Express - node.js

I am trying to build a full stack app using ReactJS for the frontend and ExpressJS for the backend. I use Axios to make calls from my frontend to my backend. When I make those calls, I get these errors:
My express index file:
const express = require('express')
const path = require('path')
var app = express()
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
My get call from React frontend:
componentDidMount() {
axios.get("http://localhost:5000/servers.json").then((res => {
this.setState({ servers: res.data })
}))
}
React server is running on port 3000 and Express server is running port 5000, so there shouldn't be a conflict there...

The reason you are getting the error http://localhost:3000 is not allowed by Access-Control-Allow-Origin is because of the same origin policy, a security feature that's restricting your react script from accessing/communicating your server since they are from different origins. Please note that for documents or scripts to be considered as having the same origin they need to have the same protocol (e.g http / https), hostname (e.g localhost / www.my-server.com) and port. In your case port the react script runs at port 3000 while the express script is running on port 5000, thus the error.
To solve this, you need to enable CORS - Cross Origin Resource Sharing on your server side code. First install the cors dependency using the command
npm install cors
Then update the code in your server to look as follows:
const express = require('express')
const path = require('path')
const cors = require('cors')
const app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
Hopefully this works for you.

This looks like a basic cors issue. Add this cors middleware to your express server. It's the state of the art solution to this problem.
const express = require('express')
const path = require('path')
var cors = require('cors')
var app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
If you are interested about cors in general, check out the wikipedia page.

Related

Routes are not working in cPanel deployed json-server

I recently tried to deploy json-server to my interserver's shared hosting plan via cPanel.
I uploaded the app and configured a Node.js app and I'm able to access the endpoint via 'https://soltonbaev.com/json-server/api/contacts' however the jsonServer.rewriter() is not rewriting the "/api/" route to the "/".
In addition I cannot access the individual object via it's id, like for instance "https://soltonbaev.com/json-server/api/contacts/1". Server returns 404.
So clearly, JSON server is not picking up the routes when it is supposed to.
Here is the content of my server.js file
require('dotenv').config();
const jsonServer = require('json-server');
const cors = require('cors');
const server = jsonServer.create();
const router = jsonServer.router('database.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3000;
server.use(
jsonServer.rewriter({
'/api/*': '/$1',
})
);
server.use(cors({origin: process.env.REMOTE_CLIENT_APP, credentials: true}));
server.use(middlewares);
server.use(router);
server.listen(port, () => {
console.log(
`🚀 JSON Server is running on ${process.env.REMOTE_CLIENT_APP}:${port}}`
);
});

Full Stack: Http failure response for url: 0 Unknown Error

I am trying to deploy my full stack application built using MySQL, Express, Angular and Node on Plesk Obsidian. However, I am facing an issue during the deployment. When my client side sends a request to the server then, I get the following error:
"Http failure response for https://example.com:3000/api/mytargetapi: 0 Unknown Error"
"GET ... net::ERR_CONNECTION_REFUSED"
Everything was working smoothly until I deployed it on Plesk.
Here's my code of the request on the client side:
const params = new HttpParams().set('id', this.searchInDirectory);
this.http.get('https://example.com:3000/api/mytargetapi', {params})
.subscribe(response =>
{
this.itemDisplay = response;
}
server side:
var app = express();
app.disable('x-powered-by');
app.use(bodyParser.json());
app.use(cors());
app.use(routes);
const port = process.env.PORT || 3000;
const host = 'localhost';
const server = http.createServer(app);
server.listen(port, host, () => {
console.log(`Running on port ${port}`);
});
router.get('/api/mytargetapi', (req, res) => {
stuff here...
}
Does anybody know what am I doing wrong? I have searched the same question on stack overflow and followed each and every individual's solution but nothing seems to be working for me. Any help would be appreciated. Thanks!
I don't know how you're organizing your project structure for the back-end API, but you should test the API via POSTMAN before integration with your front-end client
var app = express();
app.disable('x-powered-by');
app.use(bodyParser.json());
app.use(cors());
app.get('/api/mytargetapi', (req, res) => {
stuff here...
}
app.use(routes);
const port = process.env.PORT || 3000;
const host = 'localhost';
const server = http.createServer(app);
server.listen(port, host, () => {
console.log(`Running on port ${port}`);
});

localhost:3000 not responding

I've just started learning node.js but when I try to launch the hello world code by writing on the terminal node server.js, localhost:3000 gives me the following error:
This page isn’t working;
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
I've been searching for 2h now and I've found nothing. I've checked the port 3000 in cmd with netstat -a -n -o and it says that the port is listening (so I guess it is working). So what is preventing me from accesing to that port.
Here it my JS files:
server.js:
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer();
server.listen(port);
app.js:
const { request } = require('express');
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.status(200).json({
message: 'It works'
});
})
module.exports = app;
Add the required app to the createServer call:
const server = http.createServer(app);
In this way the http server can route your http requests to it.
Could process.env.PORT be set somewhere, causing your app to be hosted on that port instead?
An easy way to check would be to console.log the PORT variable in your script, and see if it has any value.
If it does have a value, trying going to localhost:PORT

Running Swagger JSON through Swagger UI via node

I have done npm install swagger-ui-express in the root folder of the project and kept a swagger.json as well there. My app.js contains:
var swaggerUi = require('swagger-ui-express'),
swaggerDocument = require('./swagger.json');
const express = require('express');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// app.use('/api/v1', router);
const server = app.listen(3000, function () {
let host = "localhost"
let port = 3000
console.log("App listening at http://%s:%s", host, port)
})
I have created a folder api-docs as well inside the root project folder. When I run in terminal node app.js and see in the browser localhost:3000, it displays
Cannot GET /
What can be the issue?

Express launching Angular application

I have an express server setup online which loads multiple ports and those ports are setup on subdomains for example. port 9000 loads the main domain.com port 8000 loads the main application at "app.domain.com" port 1000 loads "signup.domain.com" and the build version of the app is on port 8500 "build.domain.com".
The application is an Angular application however when I go to load the Angular app it loads on port 4200 or it says 8500 is in use. So currently I am loading that in express like so:
// Build Application - In Development
var appbuild = express();
appbuild.get('/', function (req, res){
res.sendFile('/app/build/myapp/src/index.html', { root: '.' })
});
var port = 8500;
appbuild.listen(port);
console.log('Build App Listening on port', port);
So my question is in Express how can I instead of writing sendfile command make it launch the angular app in that location on port 8500 so my subdomain names will work. The reason I'm asking this is because right now all it does is load the index file but angular or the app isn't running so i just see source code that says app-root and a blank white page.
Thank you in advance.
Robert
--- Update. I've decided to post the entire Express file. My issue is trying to load a angular app on port 8500 from the subfolder upon booting of express. Here is the full server.js code:
// server.js
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('../config/DB');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
// Main Website
var web = express();
web.get('/', function (req, res){
res.sendFile('/web/index.html', { root: '.' })
});
var port = 9000;
web.listen(port);
console.log('Web Listening on port', port);
// Main Application
var app = express();
app.get('/', function (req, res){
res.sendFile('/app/index.html', { root: '.' })
});
var port = 8000;
app.listen(port);
console.log('Main App Listening on port', port);
// Build Application - In Development
var appbuild = express();
appbuild.get('/', function (req, res){
res.sendFile('/app/build/myapp/src/index.html', { root: '.' })
});
var port = 8500;
appbuild.listen(port);
console.log('Build App Listening on port', port);
// Sign up Portal
var sign = express();
sign.get('/', function (req, res){
res.sendFile('/signup/index.html', { root: '.' })
});
var port = 10000;
sign.listen(port);
console.log('Sign Up Portal Listening on port', port);
Refer to this link https://malcoded.com/posts/angular-backend-express
Update your code to the following:
const express = require('express');
const app = express();
app.listen(8500, () => {
console.log('Server started!');
});
You need to build the angular app if your angular version not 1.x
ng build
Also, I think this question is similar to your question:
Not able to view Angular app via express/heroku?

Resources