Set up proxy server for create react app - javascript

I have started a react application using create-react-app and ran the npm run eject script to gain access to all files. I afterwards installed express and created server.js file that sits on same level as package.json file
these are server.js file contents:
const express = require('express');
const app = express;
app.set('port', 3031);
if(process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
}
app.listen(app.get('port'), () => {
console.log(`Server started at: http://localhost:${app.get('port')}/`);
})
Nothing crazy here, just setting up for future api proxies where I need to use secrets and as I don't want to expose my api.
after this I added a "proxy": "http://localhost:3001/" to my package.json file. I am now stuck as I need to figure out how to start my server correctly and use this server.js file in development mode and afterwards in production.
Ideally It would also be good if we could use more that one proxy i.e. /api and /api2

You didn't have to eject to run your server.js. You can just run it with node server.js together with create-react-app.
You can still do npm start even after ejecting to start your dev server.
To run /api1 and /api2, you just have to handle it in your server.js file and it should work just fine. You need to match the port in your server.js and the one in proxy settings inside package.json - in this case, it should be "proxy": "http://localhost:3031"

Related

how to deploy nodejs api and vuejs app in one server

I have developed node rest api and vuejs web applications,
Im trying to deploy both project in to one aws server which run ubuntu.
Both applications have different port,
domain I try to configure api.example.com for api and example.com for vue app.
I can run both applications once after running the command in SSH, but I need them to run it forever.
What I did,
Deploy to apps separately
Apps can access with ports
I need them access
api.example.com
example.com
what are the step to do,
Any changes host file.
I found another way to deploy vue app and express/nodejs in one server without using PM. This what I did
Build your vue code using npm run build command. This will create a folder dist which should have index.html file and static folder.
Copy dist folder into your server code repository. In my case I created a folder public and moved the dist folder inside public.
In app.js file right before module.exports=app line, copy the following lines of code
//These 2 lines make sure that vue and express app are coming from the same server.
app.use('/static', express.static(path.join(__dirname,"../public/dist/static/")));
app.get('/', function(req,res) {
res.sendFile('index.html', { root: path.join(__dirname, '../public/dist/') });
});
First line make sure that the /static folder is accessible and second line will serve the index.html file when you run the node server. Routing between components will be taken care by vue.
This is how we are running our VueJS UI and ExpressJS REST API from the same server.
We are managing our services with PM2.
VueJS (Dev Environment, You can add the same settings to production)
In package.json add "start": "HOST='0.0.0.0' PORT=80 npm run dev",, where 80 is the port VueJS is listening on, to the "scripts": {..} array. Then, after installing PM2, (for dev) we can start VueJS with cd /location/of/vue/root; sudo pm2 start npm run dev --name Vue -- start. (Make sure that Apache is not running).
Please note that setting the HOST to 0.0.0.0 is important. Do not set it to LocalHost or your Servers IP address or you may run into issues.
ExpressJS
In the /location/of/express/app.js add this similar to the bottom of the file:
app.listen(process.env.PORT || 8081), where 8081 is the port your REST API should be listening on. I can then start it with sudo pm2 start /location/of/express/app.js --name Express
At this point, the VueJS should be available at www.example.com (implied Port 80) and the REST API would be available at www.example.com:8081.
If you want to have api.example.com/ point to the API, you need to make sure that your DNS is pointing the "api" subdomain to the desired port, or you may have to add the port into the URL as above.
Additionally, you can easily follow the logs through PM2 as well with pm2 logs APPNAME --lines 100.

How to deploy a Vue.js application on Node.js server

I have a dist folder containing CSS, fonts, JS folder and an index.html file minimized for Vue.js, ready to deploy and use. I want to use Node.js to run this application. How can I set this up to just run npm run server and have it deployed on a specific port requested? Not sure how to structure this or if I need to build it in a specific way to run this Vue app. Any help would be greatly appreciated.
Since Vue is only a frontend library, the easiest way to host it and do things like serve up assets is to create a simple Express friendly script that you can use to start a mini-web server. Read up quickly on Express if you haven’t already. After that, add express:
npm install express --save
Now add a server.js file to your project’s root directory :
// server.js
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 5000;
var hostname = '127.0.0.1';
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
after that you could run :
node server
and your project will be served at the given host and port
Assuming that you have already the dist directory, if you don't have it run :
npm run build
in order to generate it

Node.js file to run a local server with access-control-allow-origin

I have an html file that has resources in it's directory
(example file tree)
index.html
imgs
>img1.jpg
>img2.jpg
>img3.jpg
js
>js1.js
>js2.js
How do I run a node.js server that will allow me to view the HTML file, as well as allow me to access certain websites with the access-control-allow-origin *
I am unfamiliar with node, so the simpler, the better!
Extra: does not necessarily have to be node, just a server that will allow access control
Since You're learning and starting from scratch so it's preferred to learn how it's done than installing supper-pupper swiss knife toolset that will hide the logic from You and make You boring lazy developer.
If You just want to achieve quick result and don't want to learn - You may use serve package that will do what You need.
But if You're learning nodejs from zero to hero so read my answer.
It's better to do simple things.
Let's go (:
Create some folder and inside of it do following commands in terminal (or cmd in windows os):
1) Init app:
npm init
2) Install express module:
npm i --save express
3) Install cors module/middleware:
npm i --save cors
4) Create public folder and put Your html files there
5) Create app.js file in sibling folder with public:
"use strict";
const
express = require('express'),
app = express(),
cors = require('cors');
app.use(cors()); // attach cors middleware (must be set before of most route handlers to populate appropriate headers to response context)
app.use('/', express.static('public'));
app.listen(8080, () => console.log('APP STARTED'));
6) Run it: node app.js
7) Open in browser: http://127.0.0.1:8080
for more stuff search in YouTube for nodejs express tutorials, nodejs mean stack tutorials and etc. (:
For a quick resolution it can also be checked, the Chrome Web server app, for creating local server allowing access to the local files over localhost server.
https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb

React + Express - What to serve instead of /build when in development

I used create-react-app to initialize my React app, and I am now serving the React client app from an Express server.
My app structure is
project/
build/
server/
src/
where my Express server is in server/, my React app is in src/, and the React app gets built to build/ with npm run build.
Because my Express app serves the "built" app (as shown below, serving files from the build/ directory), I need to npm run build every time I change any client code, in order for my browser to reflect the changes.
// server/app.js
const express = require('express');
const path = require('path');
const app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
// sockets
require('./sockets')(io);
// serve main file
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
module.exports = server;
Since the build step takes many seconds, this is obviously a big step down from when just serving the React app with react-scripts start and having it watch for code changes and instantly reflect them in the browser.
I know I can use NODE_ENV === 'production' to check if I'm on production or development, but given I'm on development, where are the files I should serve instead of the ones in build/?
I.e. perhaps a relevant question is "from where are they being served when I run the React server with react-scripts start"? EDIT: and how are they being watched such that building the source files to that spot is extremely quick?
Most of the react boilerplates use [webpack dev server / browserify] + hot reload in dev mode, so your changes (and only your changes) are compiled on the fly and your browser is refreshed by a watcher.
It's basically a middleware you plug to express like that
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
app.use(devMiddleware)
It's done under the hood in your case, the files are written in memory.

How to prepare an angular.js app to deploy to Heroku?

I have built an Angular.js quiz app by following a video. I don't understand the workings of the app yet, but it works fine with Mozilla Developer Edition, not with other browsers because I run it locally. My app's root directory contains the main HTML file, a JSON file, a folder for the CSS file, a folder for the images, and a folder for Angular.js files.
When I try to deploy the app to Heroku, it gives me an error message saying 'No default language could be detected'. It has something to do with build packs. I am unable to figure it out. Here is the link to my repo on GitHub:
My repo on GitHub
Heroku supports node server so create a basic node server for your angular application
Install NodeJS and type npm init from project folder to initialise the package.json file.
Install these packages gzippo, express, morgan. Run this command from terminal.
npm install --save gzippo express morgan
server.js
var gzippo = require('gzippo');
var express = require('express');
var morgan = require('morgan');
var app = express();
app.use(morgan('dev'));
app.use(gzippo.staticGzip("" + __dirname + "/"));
app.listen(process.env.PORT || 5000);
Create a Procfile (remember file without any extension)
Procfile
web: node server.js
Now try deploying your branch on Heroku

Categories

Resources