React & Node JS deployment on Apache server - javascript

I am trying to deploy my react app with node js as a backend on apache server on a shared hosting. My folder structure is lke following:
client //frontend folder along with build folder inside it "created
by npm run build"
config
controllers
models
node_modules
routes
package.json
package.lock.json
server.js
I have checked numerous tutorials and articles on the internet but failed to deploy it. Do I need to create ".htaccess" file? Can anyone guide me how to deploy it properly.
My server.js code:
// ROUTES
app.use("/api/sms", sms);
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "/client", "build", "index.html"));
});
//CONFIGURE PORT
const PORT = process.env.port || 5000;
const server = app.listen(PORT, () =>
console.log(
`Server running in "${process.env.NODE_ENV}" mode on port "${PORT}"`
)
);

Related

Static files not showing on express server

I am currently trying to get my JS express server to display my static HTML files using this code.
My JS Express code
**When I run my server I get this error message Error: ENOENT: no such file or directory, stat: and the directory path to the file. the directory path exists so I don't understand why it wont show the file and its contents. could someone explain this to me please. **
What I have tried in addition to my written code.
**I have tried changing the location of my project entirely and that didn't work.
I have tried using app.use, __Fileneme instead of __dirname, rewriting the code nothing works.
Im using Node. js I have express installed and required I have rewritten the code several times to be sure the error was not syntax error "although VS code would have made me aware of any syntax errors" I just at a loss now. this is a simple server that should display my html files just fine yet nothing I do works.**
try adding this line at the top:
// where /public is the folder where 'welcome.html' is
app.use('/public', express.static(__dirname+'/../public'));
the npm path package may be helpful as well
app.get('/Home', (req, res) => {
console.log(path.join(__dirname ,'/public/welcome.html'));
res.sendFile(path.join(__dirname ,'/public/welcome.html'));
})
const express = require('express');
const app = express();
app.use(express.static('public',{
extensions: ['html', 'htm']
}));
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});

node index.js command start and end server in the same time

I did install WSL2 and ubuntu 22.04 distribution on windows 11. I configured envoirment, installed nvm, node v.16.17.1, next in my folder did npm init, installed express, created index.js file within simple structure:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
When i tap node index.js nothing happen.
image
In my second computer with ubuntu 20.04 distribution everything work fine. Does anyone know what to do?
How about doing debugging by referring to https://expressjs.com/en/guide/debugging.html?
like this,
DEBUG=express:* node index.js
If no other problem is found, it would be good to use the --inspect options.
https://nodejs.org/en/docs/guides/debugging-geting-started/
Problem resolve. File need to be SAVE before calling from terminal....

Nuxt & Express server not getting api requests in production /dist

I have a Nuxt app running successfully on my local server and all API requests are successfully running from the same server (using the serverMiddleware property in nuxt.config.js). When I run a yarn generate, the path to the API server is lost and no data is loaded. Below are a few screenshots.
Loads data successfully from the API.
Unable to find API
Here is an example of an api call in project_dir api/index.js file
const express = require("express");
const passport = require("passport");
const allRoutes = require("../api/routes/routes");
const guestRoutes = require("../api/routes/guest");
const fileUpload = require("express-fileupload");
const path = require("path");
// Create express instance
const app = express();
// Init body-parser options (inbuilt with express)
app.use(express.json());
app.use(fileUpload());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "../", "dist")));
/**
* -------------- PASSPORT AUTHENTICATION ----------------
*/
// Need to require the entire Passport config module so index.js knows about it
require("./config/passport-jwt");
// Initialize Passport
app.use(passport.initialize());
/**
* -------------- ROUTES ----------------
*/
// Imports all of the routes from ./routes/index.js
app.use(guestRoutes);
app.use(passport.authenticate("jwt", { session: false }), allRoutes);
console.log("express");
console.log(path.join(__dirname, "../", "dist"));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../", "dist", "index.html"));
});
// Export express app
module.exports = app;
I don't know why I'm not able to get data from the API routes which I'm running on the same server.
Here is an in-depth answer on how to run an Express server alongside Nuxt: https://stackoverflow.com/a/72102209/8816585
First thing to know, is that you cannot have a Node.js server with yarn generate because it's using target: 'static' and as you can guess, when something is static, it doesn't need a Node.js server to be served to the end-user (only the html + css + js static files are hosted on a CDN or alike).
This mode is meant to host the code on Netlify, Vercel or alike, with no Node.js server available there.
Why is it working locally? Because you do have a Webpack dev server running (with a Node.js server so) for debugging purposes like HMR etc...
TDLR: this is normal (works as intended so far). More info on the given link above on how to make it work.
After much research and debugging I came up with a new idea.
Instead of running npm run start or yarn start containing script "nuxt start" inside the package.json file. I added a new script with the name "express-start": "cross-env NODE_ENV=production node api/index.js". Which runs the express server and nuxt static files.
I'm currently creating a template to make it easier for those who'll face this challenge.
Link to a boilerplate I created after solving the issue.
ExpressJs & NuxtJs Boilerplate

how do you start an express server with react on heroku?

I have managed to get my app working on heroku and I can hit the url and it loads successfully.
the problem is this is just the React frontend (locally I fire up on port 3000). I then also use an express node server as my backend for my api end points and then firebase as my data. when running locally I have been firing it up on 3007. however, I've just deployed and it's running the frontend but none of the API calls are being made (I presume it has not started the server)
how can I link the 2 up or tell heroku to run the other server command as well?
Imagine you have folder structured
-main folder
--client folder
--server stuff
try writing in server's package.json
"scripts": {
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
}
then deploy project to heroku from server folder's level
this will build your client during the time you're deploying your whole project
#edit
also add
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"));
});
}
to server's index.js file

How to install Angular and Nodejs in the same folder

I am new to NodeJs and Angular and I have created simple Nodejs application using this link but there was no example on how to install Angular alongside Nodejs. I tried running ng new angular-crud in the root folder and it created angular-crud folder within the root folder. Now I have 2 node_modules folder, first in root folder and second in angular-crud folder.
a) INSTALL ::How to install Angular so that there is always only one node_modules folder.
b) RUN ::Nodejs application is run using command node app.js where app.js is the entry point but on the other hand Angular application is run using ng serve.
If I have both the Nodejs and Angular installed then how to run the application.
c) STRUCTURE:: What should be the ideal folder structure when using Node and Angular together.
My package.json file:
{
"name": "test-na",
"version": "0.0.1",
"dependencies": {
"body-parser": "^1.18.3",
"cors": "^2.8.4",
"express": "^4.16.3"
},
"description": "test",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
My app.js file:
const bodyParser = require('body-parser');
const express = require('express');
const cors = require('cors');
const app = express();
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(bodyParser.json());
app.use(cors(corsOptions));
app.route('/api/cats').get((req, res) => {
res.send({
cats: [{ name: 'lilly' }, { name: 'lucy' }]
});
});
app.route('/api/cats').post((req, res) => {
res.send(201, req.body);
});
app.route('/api/cats/:name').get((req, res) => {
const requestedCatName = req.params['name'];
res.send({ name: requestedCatName });
});
app.route('/api/cats/:name').put((req, res) => {
res.send(200, req.body);
});
app.route('/api/cats/:name').delete((req, res) => {
res.sendStatus(204);
});
app.listen(8000, () => {
console.log('Server started');
});
Angular is intended to create single page applications: if you won't perform server side rendering, you probably shouldn't embed an Angular application within a nodeJs application.
Instead, the Angular application should live in its own folder (and, usually, in its own server), and connect with the nodeJs application by firing API calls.
For instance, you could have the domain https://acme.com to serve the Angular application statically, and your Angular application will perform api requests against https://acme.com/api/v1/.
Unless you need server side rendering (I don't know almost anything about Angular SSR), there is probably nothing you will gain by embed Angular within the nodeJs app. If you follow the Angular deploy guide, you will see that the intended form to serve and deploy Angular apps is to serve the Angular app statically from an Apache or Ngnx.
Put client and server code separated into two independent directories.
Here's a good article for these issues.
Its pretty simple, first create new angular project using angular cli or you can also clone already existing angular project. Then add folder named server, this will contain all your node server files. Let the app.js file be saved in the root (outside the server folder)
Your Folder Structure will be like the following:
e2e
src
server
node_modules
karma.conf.js
package.json
tslint.json
tsconfig.json
protracter.conf.js
README.md
app.js
You can then add required dependencies (like express, body-parser) of node server to the package.json
To serve angular through node server
Add the following line to the app.js file, dist folder will be your build folder, which will be created when you do ng build
app.use(express.static(path.join(__dirname, '/dist')));
You need to make some changes in app.js as shown below. And also, angular-cli should be installed. And then run the following commands:
ng build (dist folder will get generated automatically)
node app
Your app.js file should look like the following
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));

Categories