Deployed React Front-End not Communicating Node Back-End - Cpanel Configuration? - javascript

So I have a React frontend, and Node backend as my api connecting to mysql database. Everything works perfectly locally.
Now I have deployed to a c-panel VPS.
Front end loads as it should.
The back-end is listening, and prints out the data as it should if I type my IP address with routes into the address bar on a browswer.
However, I can get it to work typing the "domain-name + the routes". Can anyone tell me what's going on, and how to configure this is cPanel properly? I've spent days going in circles on this, and the hosting company support is no help at all.
here is a sample fetch call:
componentDidMount() {
fetch('/api/clients/all')
.then(res => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
this.setState({
clients: result.sort((a, b) => a.client.localeCompare(b.client)),
});
console.log(result);
})
.catch(error => {
console.log(error);
})
.then(
fetch(`/api/contacts/all`)
.then(res => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
this.setState({ contacts: result });
console.log(result);
})
.catch(error => {
console.log(error);
})
);
}
This is my server file with the routes in it.... I can't understand where my configuration is wrong. I think it may even be some cpanel configuration with the server, and not necessarily my code. Any help is appreciated.
const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const connection = mysql.createPool({
connectionLimit: 10,
host : 'localhost',
user : 'root',
password : 'C5pkhi6r12!',
database : 'ppr'
});
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cors());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/api/clients/all', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'handbook' table).
connection.query("SELECT * FROM clients", function (error, results) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is where the data is.
console.log(results);
res.json(results);
});
connection.release();
});
});
app.get('/api/contacts/all', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'handbook' table).
connection.query("SELECT * FROM contacts", function (error, results) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is where the data is.
// console.log(results);
res.json(results);
});
connection.release();
});
});
// Starting our server.
app.listen(8080, "0.0.0.0", () => {
console.log('Listening on port http://localhost:8080');
});

I might be late to answer, but this is how I did.
Add "Hostname": "https://YOURDOMAIN.XYZ" to package.json in react app.
Build your react app, and upload it to public_html
Use nodejs tool of cpanel.
Don't do app.listen(port, ........). Just use callback or leave it to app.listen()

Related

How to create a loop for SELECT function, to keep data updated?

I'm using an Oracle database, and every time it updates, the server doesn't understand this update and needs me to drop it for it to update the data.
const express = require('express');
const oracledb = require('oracledb');
const app = express();
var cors = require('cors')
app.use (cors())
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// Connection details for the Oracle database
const connectionString = 'dbprod';
const user = 'sapiensproducao';
const password = 'fabrica';
// Connect to the database
oracledb.getConnection(
{
connectionString: connectionString,
user: user,
password: password
},
function(err, connection) {
if (err) {
console.error(err.message);
return;
}
console.log('Connection was successful!');
// Execute a SQL query
const query = 'SELECT CODEMP,CODORI,NUMORP,SEQEOQ,DATREA,HORREA,CODPRO,CODDER,QTDRE1,QTDRFG,CODLOT,OBSEOQ from USU_VPROEXT ORDER BY DATREA DESC, HORREA DESC';
connection.execute(query, [], (err, result) => {
if (err) {
console.error(err.message);
return;
}
console.log('Query was successful!');
console.log()
// Render the HTML template and pass the query results as a local variable
app.get('/teste', (req, res) => {
res.json(result.rows)
});
});
}
);
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
I thought of creating a loop for this SELECT function, but how can I create it?
How can I keep running this select in a loop, to keep the data always updated?
In the structure of your web server, you only ever query the database once and then create an endpoint to serve that data. Instead, create an endpoint which queries the data whenever it's invoked. Which may look more like this:
// define the endpoint
app.get('/teste', (req, res) => {
// within the endpoint, query the database
oracledb.getConnection(
{
connectionString: connectionString,
user: user,
password: password
},
function(err, connection) {
if (err) {
console.error(err.message);
// DON'T DO THIS, return an actual response to the user
return;
}
console.log('Connection was successful!');
const query = 'SELECT CODEMP,CODORI,NUMORP,SEQEOQ,DATREA,HORREA,CODPRO,CODDER,QTDRE1,QTDRFG,CODLOT,OBSEOQ from USU_VPROEXT ORDER BY DATREA DESC, HORREA DESC';
connection.execute(query, [], (err, result) => {
if (err) {
console.error(err.message);
// DON'T DO THIS, return an actual response to the user
return;
}
console.log('Query was successful!');
console.log();
// return the results to the user
res.json(result.rows);
});
});
});
The key difference here is that instead of wrapping the endpoint in the query, you wrap the query in the endpoint. So every time the endpoint is invoked it re-queries the database.
Please also note the comments for your error handling. If you just return; from the function and never return a response to the client, the client will just hang until it times out. Return an actual response, which can include error codes, messages, anything you like. Even just res.json(false); would be better than no response at all.

Unable to Set Cookie in Node JS - React

I am using Node JS on serverside and React on client side. On successful auth when i try to use res.cookie and set a cookie. On client side however the Cookie only shows up in Network tab and does not get set in application tab. I am using axios for making the request and have even set the credentials header to include since I am using cors. Here is my code below
router.post("/", (req, res) => {
console.log(req);
const email = req.body.email;
const password = req.body.password;
loginService.login(email, password, (userPublicData, token, err) => {
if (err) {
res.status(401);
res.send({ user: null, error: err });
} else {
res.status(200);
res.cookie("jwt", token);
res.send({ user: userPublicData, error: err });
}
});
});
Here is my client side function
async function authenticateUser() {
console.log(values);
axios.defaults.headers.common["credentials"] = "include";
axios
.post("http://localhost:8080/api/login", values)
.then(response => response.data)
.then(dataJson => {
sessionStorage.setItem("userData", dataJson);
props.history.push("/admin");
})
.catch(err => {
console.error("Auth error", err);
});
}
The cookie appears in network tab but doesnot get set in the application cookies. Some help would be much appreciated

how to create rest api using node.js express js and oracledb for update database

i am new to node.js and want to create api for getting data and update that data on frontend,please give me solution for this,i am getting data from this code but unable to update data.I am using react js for frontend.
var express = require("express");
var app = express();
var oracledb = require('oracledb');
var dbconfig= require('./dbconfig')
(async function () {
let connection
try {
connection = await oracledb.getConnection({
user: 'dbconfig.user',
password: 'dbconfig.password',
connectString: 'dbconfig.connectstring'
});
var result = await connection.execute('select * from
PROPERTY.app_booklet_challan_detail', []);
console.log("Successfully connected to Oracle!")
console.log(result)
} catch (err) {
console.log("Error: ", err);
} finally {
if (connection) {
try {
await connection.close()
} catch (err) {
console.log("Error when executing the database connection: ", err);
}
}
}
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
next();
});
app.get('/list', (req, res, next) => {
res.send(result);
next()
});
app.put('/list/update', (req, res, next) => {
let STATUS=res.data
connection.execute('UPDATE PROPERTY.app_booklet_challan_detail SET STATUS= ? WHERE
BOOKLETID= ? ', [STATUS])
res.send(STATUS)
next()
})
app.listen(3001, function () {
console.log("Started on PORT 3001");
})
})()
Your question is a little broad to answer with code, but I've written an entire series on this topic: https://jsao.io/2018/03/creating-a-rest-api-with-node-js-and-oracle-database/
Note there are links to a GitHub repo with the code from each module.
Once you finish with the series you should be able to take things in the direction that makes the most sense for your project.

Fetch POST to /send returns 404 error (No error in Postman)

I'm trying to upload some data to the school database when the user clicks a submit button on a form. I've set up the server.js, and it works with Postman. However, when I try to fetch (POST) the data on the button click, I get a 404 error in the browser console.
For some reason, I also can't open my html files if the server is already running. I don't know if this is relevant.
I've double-checked every string that connects the client-side fetch and the server-side app.post() together. I've also checked that the JSON data sent from my application is accepted by using the same text in Postman. This works. I've also tried looking at similar posts, but no one has the exact same problem (as far as I can tell).
This is my server.js:
let express = require("express");
let mysql = require("mysql");
let bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
let pool = mysql.createPool({
connectionLimit: 2,
host: "---",
user: "---",
password: "---",
database: "---",
debug: false
}
);
app.post("/send", (req, res) => {
console.log("Received Post from client");
pool.getConnection((err, connection) => {
if (err) {
console.log("Connection error");
res.json({ error: "connection error" });
} else {
console.log("Connection established");
console.log(req.body);
let val = [req.body.some_value];
console.log(val);
connection.query(
"insert into some_table (some_value) values (?)",
val,
err => {
if (err) {
console.log(err);
res.status(500);
res.json({error: "Insertion error"});
} else {
console.log("Insertion OK!");
res.send("");
}
}
);
}
});
});
let server = app.listen(8080);
console.log("Server running");
My client (sendButton.js):
document.getElementById("submit").addEventListener("click", function(){
let data = {some_value: document.getElementById("some_value_input")};
console.log(JSON.stringify(data));
fetch("http://localhost:8080/send", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(function(response){
alert("We're trying");
if (response.ok){
console.log("Data uploaded");
return;
}
throw new Error("Data not uploaded");
})
.catch(function(error){
console.log(error);
});
});
And the HTML button is just a standard button with an the id "submit".
My expected results: Insertion OK, values sent to the database with no error.
Actual results: 404 page not found error:
Remove the let server variable and leave the app.listen(8080), so that the end result would be
app.listen(8080, () => console.log('Server is running'));

Is it okay to include my connection in all request in NodeJS?

I have 3 files. db.js, app.js, commentController.js.
I am including my connection in every request in my app so that I wont be repeating the code connection again and again. Is this a bad / unsecure practice? Is there a better/proper way to implement this?
db.js
const mysql = require('mysql');
const pool = mysql.createPool({
host : 'host',
user : 'user',
password : 'password',
database : 'dbname'
});
exports.pool = pool;
app.js
const db = require('./db');
app.use((req, res, next) => {
req.pool = db.pool;
next();
});
commentController.js
exports.showComments = (req, res) => {
req.pool.getConnection((err, conn) => {
conn.query(`SELECT * FROM comments`, (err, results, fields) => {
conn.release();
if (err) throw err;
res.render('comments', { results });
});
});
};
If your only reason for doing this is to avoid duplicating code, then I think it's a bad idea. People looking at your code (or you looking at your code in a year) aren't going to naturally expect a db connection to be a property of req. And you aren't saving yourself any trouble really.
Just require() the database pool in the file and use it.
commentController.js
const db = require('./db');
require() will return the same pool to all your modules.
It's also not clear why you are requesting a connection rather than using the pool (I'm making some assumptions about the lib you're using).
Normally you should be able to do:
const db = require('./db');
exports.showComments = (req, res) => {
db.query(`SELECT * FROM comments`, (error, results, fields) => {
if (err) throw err;
res.render('comments', { results });
});
});
This saves the trouble of requesting and returning connections and just lets the pool do it's work.

Categories