Combine Angular 2 application server and REST server modules - javascript

I am creating a new Angular 4 application. I have followed it's official tutorial https://angular.io/tutorial/
The application server is started using ng serve command.
I have created a separate node js (+express) server that provides the REST services to the main app on a different port.
Is there any way to serve the main angular application from the same nodejs/express server so that i don't have to use two servers for the application?
I have used typescript which needs to be somehow compiled into plain javascript before statically being served via nodejs, if i understand it right?

Absolutely, just use ng build and serve the dist folder of the built application, or even the src. Example:
const staticFor = rel => express.static(path.resolve(__dirname, rel));
const app = express();
if (!config.production) {
app.use('/node_modules', staticFor('../node_modules'));
// In development we do not copy the files over, so map used path
}
app.use('/', staticFor('../dist/app'));
const appPath = path.resolve(
__dirname,
config.production ? '../dist/app/index.html' : '../src/app/index.html'
);
app.get('/yourAppPath/*', (req, res) => {
const markup = fs.readFileSync(appPath, 'utf8');
res.send(markup);
});
Dont forget to require the right libraries.

Related

Rendering react with node.js in development

I am (very) new to node.js and I am trying to get a development environment started with React.
const express = require('express')
const mongoose = require('mongoose')
const app = express()
// this displays the index.html file
app.use(express.static(__dirname + '/public'));
// trying to see the app.js
app.get('/', (req, res) => {
res.render('app')
})
app.listen(process.env.PORT || 5000);
Right now I am simply trying to be able to view my app.js when I run nodemon. But right now it is only showing the index.html file in the public folder. and when I run npm start it renders both the index.html and the app.js.
I am 100% doing something wrong and am not in my element here. Any help/advice would be appreciated.
My full repo is here for viewing here
Thank you in advance.
Your code is simply serving a static HTML file located in the public directory everytime the user make a GET request to the root (in your case, localhost:5000). It is not interacting with React yet.
Usually when starting a project with React (frontend) and Node (backend), you would create them as separate projects, in separate repositories.
So you could create a React application using a bootstrap such as create-react-app running on PORT 3000 and in another terminal tab, start your NodeJS application in PORT 5000 like in your example. Then, you can call your backend endpoint from your frontend React application, by referencing http://localhost:5000
By doing this, your backend code don't need to serve static files anymore, it can return data such as JSON and make connections to a database for example.
Since your question is not specific enough, you could be talking about server side render. In server side render apps using Node and React, you have a frontend built with React and a Node server that will return the same React code as a string, using the react-dom/server package to help. This is more complex, but basically you will have the same React code on the client AND on the server. There are performance benefits, because the user can see some content rendered right when he enters the page, without having to wait the React bundle (javascript file) to load. If you want to know more about creating a server side render app with React and Node, there is a nice digital ocean tutorial here
If you want to connect your react js project to the node js
In Development
you simply run their server and start it
In Production
You can use sendFile function coming from express.js to run the frontend
https://dev.to/loujaybee/using-create-react-app-with-express

Access a local directory to retrieve files from localhost and write back

I currently have an Angular app (MEAN Stack) that I am running locally on my Windows machine. Being new to Node/Express, I would like to be able to access a local directory from http://localhost:3006 that I have setup within my main app directory, called /myfiles which I am unsure how to do.
What I am unsure is, how do I create an endpoint to access and read these files from localhost within the /myfiles directory and display them within an Angular Material dialog?
Just not sure what I need to do as part of Express side (setting up the route) and then the Angular side (using HttpClient) to display.
Further to the above, I will also need to write back to the /myfiles directory, where I will need to perform a copy command based on a file selection within Angular.
You'll want to create an endpoint in Express that your Angular app can call to be served the files.
I'll assume the files you want to read and send are JSON files. Here's a really simple example of an endpoint that you can visit that will return the file to your frontend.
In your Angular code you will make a get call to /myfile
var fs = require("fs");
app.get('/myFile', (req, res) => {
var filepath = __dirname + '/myfiles/thefile.json';
var file = fs.readFileSync(filepath, encoding);
res.json(JSON.parse(file));
});
Then in Angular, you'll have something like
http.get('/myfile').subscribe( (data) => { console.log("The data is: ", data) });
ADDED
The example I provided above was just the basics to answer your question. Ideally, in production for file paths, you should the Node path library which 'knows' how to behave in different environments and file systems.

How to Integrate angular 4 or higher with express

i want to integrate angular 4 or higher than that with my existing express folder.
As i am new to mean stack development i want clean and understandable steps how to integrate angular with express.
Anyone having reference links for the following::
How to integrate express and angular
how to use mongoose in it.
And crud example for mean app development.
Integrating Angular and Express can be done through a single server.js file placed in the root directory of your Angular project. Use Angular CLI to ng build --prod and generate a dist/ folder. You can then link the dist/ folder through the following code in your server.js file and running node server.js.
// Define variables
const express = require('express');
const app = express();
// Use the /dist directory
app.use(express.static(__dirname + '/dist'));
// Catch all other invalid routes
app.all('*', function(req,res){
res.status(200).sendFile(__dirname + '/dist/index.html');
});
// Start the server
app.listen(process.env.PORT || 3000);
The Mongoose Docs are very good, but if you need a video, this one: Mean Stack Front to Back: Part 3 is a nice code-along you can work with. The Mongoose part starts about 90 seconds into the video.
This website gives a nice CRUD Example and also goes into Mongoose as well.

ReactJS and NodeJS same server?

I build a project with nodejs and react. I don't know if I must split in 2 servers, one for the react app and one for API in nodejs and the react app ask request at nodejs server.
Or I must group both in only one nodejs process ? What's the difference ? There are a better choice ?
It's up to you React when builded is just static files, don't get confused by the development server. I would recommend you for the beginning to put them in one node process. Just declare the folder of the static files like this:
app.use('/app', express.static(path.join(__dirname + '/dist/app')));
Also if you are using React Router you should add this as your last router
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/src/index.html'));
});
You can check my template repo with webpack here

Convert Nodejs server into node module

Is it possible to convert a nodejs API server into a node module, which can be used for other projects without making much code changes?
Details: There are several API's(get, post, put) in the node js server. So if I use this server as a node module inside another node server, I must be able to access the API's in the node modules directly from the client. Is this possible? If yes, how?
I am required to do a POC on this for a client requirement and so far did not find it possible. Can you please help? I am relatively new to node js development
main script
const express = require('express');
const app = express()
/*
use some middlewares
*/
require('my-module')(app)
const server = http.createServer(app).listen(process.env.PORT);
module.exports = app;
module
module.exports = (app) =>{
app.get('/',(req,res) =>{
res.send('hi im a diffrent module;')
}
}

Categories