ReactJs read localhost basename - node.js

I have frontend running on http://localhost:3000/ and backend running on tomcat 10 in http://localhost:8080/my-app and sometimes backend in http://localhost:8080/your-app. My problem is if i change the backend from my-app to your-app. i dont know how to my frontend can get the basename your-app automatically. i think its very annoying if changing the basename variable in frontend everytimes i change the backend route.
i have try to put basename as env.variable but i want to get the route automatically

You can not find your backend url automaticly with react or javascript tricks.
usualy, I determinate it in public/index.html :
<script>
window.myApp = {
apiBaseURL = "http://localhost:8080/my-app",
}
</script>
and in all Component I have access to it :
function App(){
const baseURL = window.myApp.apiBaseURL;
}
another method define base url in .env file

Related

express app is not sending index.html file to client

So my express app has a small Node server setup so it can serve up the index.html file when the home route '/' is hit. This is a requirement of using the App Services from Azure, there has to be this server.js file to tell the server how to serve up the client, and i had a previous implementation of this working, however i wanted to change my file structure. previously i had, the client React app in a folder client and the server.js in a folder server along with all of the conrtollers and routes. i've since moved the server API to its own application as there are other apps that depend on it. and i moved the client up one directory into the main directory. Everything was working fine till the other day when all of the sudden when you hit the home route / it will not serve up the index.html file. if you hit any other route it works, if you even hit a button linking back to the homepage, it works, but it wont serve up the app from the / and i cannot for the life of me figure out why, on my development server there are no errors in the console. and im most definitely targeting the correct directory and place for the index. but its like the server isnt reading the route to serve up.
if (process.env.NODE_ENV === 'production') {
console.log('running');
app.use(express.static(path.resolve(path.join(__dirname, 'build'))));
// no matter what route is hit, send the index.html file
app.get('*', (req, res) => {
res.sendFile(path.resolve(path.join(__dirname, 'build', 'index.html')));
});
} else {
app.get('/', (req, res) => {
res.send('API is running...');
});
}
So here im saying if the NODE_ENV is in production make the build folder static, and then whatever route is hit. (Note: i also tried this app.get with other route formats such as /* or / all have the same issues. however in my previous iteration when the client and server where deployed in the same location, /* is what i used.) The .env varialbes are setup correctly, as when the server is ran, itll console log running.. but even if i put a console log inside of the app.get() its like its never hit unless i access the route from something else first.
for example, if i place a console log inside of app.get that states hit whenever the route is hit, hitting / directly does nothing, but if i go to /login itll serve up the correct html on the client and console log hit in the terminal...
If you are having server files inside the client react app, then we are basically accessing file which are not inside our server file. So, we can serve static files using the following code:
const express = require("express");
const app = express(); // create express app
const path = require('path');
app.use(express.static(path.join(__dirname, "..", "build")));
app.use(express.static("build"));
app.listen(5000, () => {
console.log("server started on port 5000");
});
Now in your packages.json of the client react app change the name of start tag under scripts tag to start-client. Then add this following tag to the scripts tag:
"start":"npm run build && (cd server && npm start)",
Basically, this will build the react app and start the server.
It should look like this :
Also in the packages.json of your server add the following tag under script tag
"start":"node server.js"
So when you run the following command npm start it should look like this :

.env is not being read in create-react-app

I have created a react app using create-react-app. I'm using react-admin to develop my admin panel. I want to use some environment variables. Here's my .env file:
REACT_APP_API_URL=http://localhost:8000
REACT_APP_BRAND=Guli
REACT_APP_SLOGAN=Financial transactions, redefined
And I also have .env.test and .env.production for staging and production environments, and I only override API URL in those files.
Now I want to use these variables inside my react app. I'm using them inside index.html and DataProvider.js that I use for react-admin.
In index.html I use:
<title>%REACT_APP_BRAND%</title>
and in DataProvider I use:
const apiUrl = process.env.REACT_APP_API_URL;
// using apiUrl in the rest of DataProvider.js
The problem is that none of these variables are read from .env file. In index.html I see the title of my app to be exactly %REACT_APP_BRAND%, and the calls to my API go to undefined/users for example which means that process.env.REACT_APP_API_URL is not loaded.
What sould I do?

How do I proxy requests for static files on my node server to my react development server?

I have a node.js server that serves the built static files of my create-react-app at /admin. The problem is that anytime I make a change to my react app I have to build the files over again to see the updates. Instead, I'd like to proxy requests for my frontend at /admin to my dev server that comes with create-react-app, running at localhost:3000, because this would allow for a much faster development experience.
This is what my server looks like now:
// app.ts
...
const app: Koa = new Koa();
app.use(mount('/admin', serve(__dirname + '/build')));
...
And this is what I tried:
import proxy from 'koa-better-http-proxy';
const app: Koa = new Koa();
app.use(
mount(
'/admin',
proxy('localhost:3000', {})
)
)
What ends up happening is the requests for static files still go out and the response gives an index.html file but the JS doesn't seem to run and it gives me errors:
Uncaught SyntaxError: Unexpected token '<'
I've also played around with the proxy header settings to adjust content-type to application/json but I had no success there either.
Due to the environment, I cannot just run the node server in one terminal and the react app in another. The request comes from a verified 3rd party and must go through my node server first before being served the frontend portion of my app.

How can I get create-react-app to use an IP to connect to my api server?

I'm using Facebook's create-react-app. When I start the web-client I see in console:
You can now view web-client in the browser.
Local: http://localhost:3000/
On Your Network: http://192.168.1.107:3000/
The problem is my web-client uses localhost to connect to the api-server, which means I can't use the IP address on different devices to debug issues.
env-variables.js:
export const ENV = process.env.NODE_ENV || 'development';
const ALL_ENV_VARS = {
development: {
GRAPHQL_ENDPOINT_URI: 'http://localhost:4000/graphql',
},
....
I tried updating the above with:
GRAPHQL_ENDPOINT_URI: `http://${process.env.ip}:4000/graphql`,
That did not work, process.env.ip is returning undefined. How can I get the above GRAPHQL_ENDPOINT_URI to use the IP address which somehow create-react-app is getting?
Try adding the following to your client-side package.json:
"proxy": "http://localhost:4000/",
You can then leave the
http://localhost:4000
off of any URLs pointing to the API server from the client side. You would just refer to those addresses as
/graphql/<any additional URL data>
I've performed the same with a Node/Express backend and a React frontend - I resolved the /api portion in my server.js with the following:
//Use our router configuration when we call /api
app.use('/api', router);
just replace /api with /graphql there.
Take a look at this article for further explanation. Hope this helps!
https://medium.freecodecamp.org/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0

Angular / Express hosting

I want to run angular on a linux box without needing node or express. I've created a website but not sure what tech is what, haha. I'm assuming I have a simple web server using express server, see code below.
var express = require ('express');
var app = express();
var path = require('path');
app.use(express.static(__dirname + '/'));
app.listen(8080);
console.log('Magic happens on port 8080');
I start this using the node server command. And the rest of the code is angular-ui.
Do I need to use express (and host this on a node compatible server), or can I just run this thing on a linux box without express? If so, do i need to replace my server.js file (above) with something else? or... Currently it's not working on the linux box, but works locally just fine.
**Edit: I tested an angular 'hello world' app on my shared server, it worked fine. When I run the full angular app on the shared server I get the following error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module routerApp due to:
Error: [$injector:nomod] Module 'routerApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
** edit: In answer to #RobertMoskal 's question below, the angular hello world test that's working on the shared server is basically this:
<input ng-model="name" type="text" placeholder="Type a name here">
<h1>Hello {{ name }}</h1>
And the real app is basically something like this, using ui-view and ng-repeat in the html:
var routerApp = angular.module('routerApp', ['ui.router']);
routerApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/home');
$locationProvider.html5Mode(false).hashPrefix("");
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
templateUrl: 'partial-home.html',
// onEnter: scrollContent
})
// ANIMATION AND NESTED VIEWS ========================================
.state('animation', {
url: '/animation',
templateUrl: 'partial-anim.html',
controller: function($scope) {
$scope.animations = [
{ title:'One', url:'http://yahoo.com', bg:'#f8f8f8', width:'160', height:'600', imageAsset:'assets/imgs/web/MyWebsites_1.jpg', paragraph:'some text of some description'},
{ title:'Two', url:'http://google.com', bg:'#f8f8f8', width:'160', height:'600', imageAsset:'assets/imgs/web/MyWebsites_2.jpg', paragraph:'rabbit rabbit rabbit'},
{ title:'Three', url:'http://bambam.com', bg:'#f8f8f8', width:'160', height:'600', imageAsset:'assets/imgs/web/MyWebsites_3.jpg', paragraph:'blahiblahblah'}];
}
})
// GAME VIEWS ========================================
.state('game', {
url: '/game',
templateUrl: 'partial-game.html'
})
// CONTACT VIEWS ========================================
.state('contact', {
url: '/contact',
templateUrl: 'partial-contact.html'
})
});
You need some web server to server your angular app as a "static" asset. This can be apache or nginx or any number of web servers. Most linux distributions make it easy to install them.
You can also go super lightweight with the built in python web server:
cd /var/www/
$ python -m SimpleHTTPServer
You can even host your application for free on github.
In all cases you you just need to make sure that the web server is serving your assets from the correct path. The above python example example you might have your app entry point in /var/www/index.html and it would be served as http://localhost:8000/index.html.

Resources