How to install Angular and Nodejs in the same folder - javascript

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

Related

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

React & Node JS deployment on Apache server

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

Deploy Node.js Restfull API and Vue.js app at the same time

I want to deploy Node.js express API and Vue.js app in the same domain with Vercel in one project.
I have one Vue.js app in root folder and i have another folder in my root folder like ./api.
I tried this script in my package.json file(In my Vue.js app.):
"serve": "vue-cli-service serve && cd api && npm run start".
This is my Node.js app's package.json script:
"start": "node index.js"
But it not works. (I know the reason of "why it doesnt work".)
How can i deploy these 2 apps in the same project?
(So i want a API works like: example.com/api/urls)
Vercel is a serverless platform, while your usage of Express is "stateful", meaning you start a long-running server process that listens for requests. Serverless, on the other hand, consists of short-running processes that spawn as needed to handle requests.
Check out this guide for using Express with Vercel: https://vercel.com/guides/using-express-with-vercel
The simplest solution is to put your entire Express app into a single serverless function (even though this is an anti-pattern):
// /api/index.js
const app = require('express')()
const { v4 } = require('uuid')
app.get('/api', (req, res) => {
const path = `/api/item/${v4()}`
res.setHeader('Content-Type', 'text/html')
res.setHeader('Cache-Control', 's-max-age=1, stale-while-revalidate')
res.end(`Hello! Go to item: ${path}`)
})
app.get('/api/item/:slug', (req, res) => {
const { slug } = req.params
res.end(`Item: ${slug}`)
})
module.exports = app
And ensure you set up a rewrite in your vercel.json:
{
"rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]
}
(these code snippets are taken directly from the guide linked above – I highly recommend following it!)
The better, serverless, approach would be to split your Express routes into their own serverless function that can be called on-demand.
Additionally, your "serve" script starting the API is unnecessary, as the top-level API directory is zero-config with Vercel. You can simply use "serve": "vue-cli-service serve".

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

create-react-app build service-worker.js and manifest.json not found

I have created an app with create-react-app. I have built it and I have written a simple express app for serving the react built app.
I have some problems with the static files and the files which are in the root folder of express app, (e.g. manifest.json, service-worker.js). Now I get 404 on both these files.
How can I treat this files in express? They must be in the static folder? I have to modify the react app?
I went to see the file generated by the react build, in which the file 'service-worker.js' is imported and the string starts with '/' (that is '/service-worker.js')
(I have not touch the files for the pwa since I created the project)
Here there's my root folder of my express app
I have only added the project.json and the index.js (and obviously the node_modules), the other files are those from the react build.
Here my express app:
const compression = require('compression');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use('/sketches', express.static('sketches'));
app.use('/static', express.static('static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(compression());
app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'))
app.listen(process.env.PORT || 3000, () => console.log('server listening!'))
Adding this line of code I get the service-worker.js but I can't get the files in the sketches folder.
app.use('/', express.static(__dirname));
I had a same problem i resolved it by following these steps.
warning: i am new to these technologies and i don't know much about web security. this maybe not the best way of doing it.
i get it work using ejs template engine and express but it should work in your case as well.
1) create-react-app
2) yarn build
3) copy static folder into public
4) copy service-worker.js inside static folder also
5) go inside main Ctrl + f
6) type /service-worker.js in search hit Enter
7) you will see somthing like that var e="/service-worker.js";
8) change into var e="/static/service-worker.js
9) finally open service-worker.js change /index.html to /
precacheConfig=[["/","d6be891ca003070326267be1d2185407"]

Categories