Dynamic routes not working in React with Caddy - reactjs

I have a React Application. I am using some routes that receives parameters in the URL (by GET), for example myapp.com/products/1 that works pretty good in local enviroment but no in my CentOS server. I have to mention that I am using npm run build to generate the static files.
For other side, I have running Caddy as HTTP server in the CentOS server, there I have problem only with the routes that includes parameters, so now am wondering if caddy have something to be with this issue.
Here the React people say:
If you’re using Apache, you need to create a .htaccess file in the
public folder that looks like this:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
So, how can I do that in Caddy. I have currently these lines for the site:
mysite.com {
root PathToProject/build/
log logs/pagelog.log
}
What is missing in order to can use parameters in the URL?

I have this config in my Caddyfile
rewrite {
if {path} not_match ^\/0.0.0.0
to {path} {path}/ /?_url={uri}
}
See if that helps, it took care of my routing issue (similar to what u have mentioned) for React App.

Related

Can't retrieve static json file from react router routes on apache server

I'm in a situation where I have to locally build a React project and then upload it to a particular path on an Apache server. It all worked alright, except it took a while to figure out how to get the Apache server to respect the react-router routes. We eventually created a .htaccess file to add to the path where my app is being uploaded and this seemed to resolve the issue:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# Fallback all other routes to index.html
RewriteRule ^ /events/new-year/index.html [L]
But I've had a request to put config variables in a json file in the /static directory so that these can be easily changed later on by the non-JS devs. Loading the JSON data from the file works just fine when in the application root. In the response I get:
{
data: {
eventDates: "20 Nov - 28 Nov"
localUrl: "http://localhost:3000"
pageTitle: "Some title"
serverURl: ""
year: "2023"
}
}
but when trying to load the json from any of the react-router routes I get a really weird output:
{
data: "<!doctype html><html lang="en"><head><meta charset="UTF-8"/><title>Current Page Title</title><link href="//www.google-analytics.com" rel="dns-prefetch"><link href="https://www.somesite.com/content/favicon-150x150.png" rel="shortcut icon"><link href="https://www.somesite.com/content....."
}
I cut most of the output because it's outputting ALL of the html for the index.html stored in the static folder. Why can't I get the a good response on these child routes?
I'm loading the json like so:
const data = await axios("./resources/data/config.json");
I've tried without the . at the front and I've tried without ./. I have found that I get a response of undefined with anything other than the ./
Thank you for reading, any help would be hugely appreciated 🙏
So it turns out that there was an issue with the path. Since the relative path didn't work (and returned html for some reason) I had to use only a / (non-relative path?). While this was returning undefined before, after looking at the network tab I realised why:
My application was sitting at www.website.com/some-path/my-application, so I needed to fetch static resources from www.website.com/some-path/my-application/resources, but instead it was looking in www.website.com/resources. So all I had to do was add /some-path/my-application to the url that I was using previously.
I hope this can one day help a lost traveller!

React router blank page for subroutes on apache

I have an app created with create-react-app that I want to deploy in my apache server.
When I tried to access my react app running on my server, i had an error 404 on every routes created with react-router. Then i added a .htaccess file in my app directory with the following rules :
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
Now i'm able to reach the simple routes, like http://mywebsite/myroute.
But when I try to reach nested routes like http://mywebsite/myroute/subroute
I've got a blank page with the following errors :
Uncaught SyntaxError: expected expression, got '<'
and
The stylesheet https://mysite/test/static/css/main.85d72dcf.chunk.css was not loaded because its MIME type, "text / html", is not "text / css"
This happen only when i try to reach a subroute, even if the routes are just html without any css.
I can't find any clue on the web, so any help would be much appreciated.
I just solved the problem by adding in the of my index.html document. For some reasons it seems to be needed when using subroutes.

ReactJS - Multi-page app not working after being built for production

I have a multi-page app that I am trying to host on GoDaddy. After running npm build, I upload the files to GoDaddy as per their instructions and I am able to view my homepage without any trouble. When I try to navigate to another page such as the about page, I get a 404 error.
I have been searching and the solutions I attempted did not work. I tried adding "homepage": "http://www.kashy.com.au/", to my package.json. I also tried playing with the routes. (Adding the URL for the site in the path).
I am new to React and so I don't quite understand how the routes work. Could someone point me in the right direction for solving this problem?
You need to redirect all urls to ur site on Godaddy to point to the homepage/index as the routing is handled by your client/react app.
Create an .htaccess file to redirect all requests to index.html.
Sample
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
Steps
From your cpanel file manager, go to the root folder of your website (ie. public_html).
Create the (dot)htaccess file, by clicking on the top left menu
Right click on the file and edit and then paste the above
Save

React doesn't load page on reload

I found a similar question here but I did't find an explenation exactly how to fix the problem. All pages on my website except index.html doesn't load when you are reloading the page. From the previousquestion I think that to solve the problem without server I need to use HashHistory but I cant' found explination how to use it. What to do in my app and what to put in my navigation. http://turbo-remont.com/
I made this website for a friend but I can't deal with this problem. Please help me.
The problem is that your server attempts to fetch the resource and not load the main file (index.htm) and then activate navigation.
and example:
Your site base is http://turbo-remont.com, if you navigate to it, your app loads and from that point on overtakes the navigation so if you go to http://turbo-remont.com/resource/1234 , it won't send a new fetch request but internally update the state and load the relevant component (as SPAs do).
When you reload the page, which is actually equivalent to navigating to the page, your server attempts to find and html file named '/resource/1234'. To overcome this, you need to instruct your server to serve index.html regardless of the full url.
I don't know what server you use, but here is a simple example of an .htaccess file that solves the problem, place it in your root directory.
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

Laravel 4 as RESTful backend for AngularJS

I am trying to build a web application which should use Laravel as a RESTful backend API and AngularJS on client side.
I read all the other post on Stackoverflow about the issue, but no one is definitely answering my doubts, at least, I did not find a definitive source example.
For instance...
Should I develop two completely distinct applications, a backend one with Laravel and another, purely client, with AngularJS?
But in this case: how to handle them through a single domain (or virtual host)?
Or should I create AngularJS templates inside Laravel, in the "views" folder and from them call Laravel services? I doubt this is the best approach: in this case the backend is not completely decoupled from the frontend implementation.
Also, how to correctly handle routing? I mean: I would like to manage from AngularJS routes like menu/page navigation, calling Laravel only to retrieve data and fill my views.
Moving the "public" folder as suggested in this post (Angular JS + Laravel 4: How to compile for production mode?) may help?
Thanx in advance for suggestions, examples...
Finally I found a working solution, perfect in my scenario, which does not require a subdomain.
In this case Laravel acts exclusively as a RESTful web service, no server side views or templates: the presentation layer is completely demanded to AngularJS.
Let's say I have two completely decoupled applications (FE e WS) inside the same root folder:
root
|__fe
|__ws
I modified virtual host settings under Apache httpd-vhosts.conf file the following way:
<VirtualHost *:80>
ServerName myapp.com
DocumentRoot "\www\root\fe"
alias /ws "\www\root\ws\public"
<Directory "\www\root\ws\public">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
I then added "RewriteBase /ws" into my laravel/public/.htacces file:
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase /ws
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [NC,L]
</IfModule>
This way I can write in the browser (for instance):
http://myapp.com (AngularJS client side root)
http://myapp.com/ws/users (RESTful service endpoint for "users")
And then define a client side, AngularJS routing the following way:
app.config(function($routeProvider) {
$routeProvider
.when('/', {controller: 'HomeController', templateUrl: 'templates/home.html'})
.when('/users', {controller: 'UsersController', templateUrl: 'templates/users.html'})
.otherwise({redirectTo: '/'});
});
Linking it to a RESTful resource this way:
app.factory('User', function($resource) {
return $resource('http://myapp.com/ws/users');
});
app.controller('UsersController', function($scope, User) {
$scope.title = "Users";
$scope.users = User.query();
});
I enabled HTML5 history API, adding this line to configure my Angular application:
$locationProvider.html5Mode(true);
together with (inside index.html head section):
<base href="/" />
<meta name="fragment" content="!" />
So the last requirement to solve problems like browser page refresh, deep linking, or direct page bookmark, is to add a .htaccess file in the root of the folder which contains the Angular application:
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [NC,L]
</IfModule>
Hope it helps!
This is a half comment half answer, it got too long.
Matteo as you pointed out there are basically three different places you can do some sort of routing/redirecting with this stack. Ordinarily I haven't seen an advantage to doing the redirects at the Apache level, I imagine this might be more useful for localization or perhaps some sort of load/disk balancing. However you will have your VirtualHost configuration if you have multiple domains pointing to this address and you need to route those initial requests to the appropriate index.html (so if you consider this routing this would be my server side routing).
Generally speaking after that I rely on the Angular $routeProvider to handle client side "routes" really just mapping a URL to a view (possibly passing along some data).
I haven't gotten fancy with setting up a router in my PHP code to create a proper RESTful interface. In my particular case the data is being stored in a fairly abstract way and I had to do a fair amount of work in the PHP to get it organized in a coherent way, any straight ORM type solution wasn't going to work. This attempt has led me to consider options like MongoDB though since it should alleviate the workload necessary for doing the translation from persistent storage to client side and back.
Anyhow all that said I use $http to just make my calls from custom services to particular PHP endpoints that I need. My PHP folder with my scripts sits right next to where my index file is served up so requests from angular are all relative paths from the server root which keeps it simple. So they are physically "nested" so to speak or living side by side but the PHP code never writes any templates or affects the presentation it just gets data and serves it up (as JSON), so conceptually they remain separate.

Resources