How does the JHipster/Angular configuration determines that it needs to use the index.html file? - angularjs

I have just generated an Spring/Angular app using JHipster.
I successfully accessed the home page by using this URL: http://localhost:8080 which redirects to http://localhost:8080/#/ and the index.html file is loaded properly.
I am not sure how Angular and the browser determine that they need to load the index.html file.
Where is this configured in a JHipster app?
edit: Is there some "default home page" configuration somewhere?

I successfully accessed the home page by using this URL:
http://localhost:8080 which redirects to http://localhost:8080/#/
The request to the server is for "/" and index.html is served. The "/#/" is all client side stuff (Angular routing) that happens when the javascript on the index.html page fires up, not the result of a server side redirect.
Where is this configured in a JHipster app?
This is a Spring Boot default, not something specific to JHipster. From the Spring Boot docs:
The auto-configuration adds the following features on top of Spring’s
defaults:
Static index.html support.
By default Spring Boot will serve static content from a directory
called /static (or /public or /resources or /META-INF/resources) in
the classpath or from the root of the ServletContext. It uses the
ResourceHttpRequestHandler from Spring MVC so you can modify that
behavior by adding your own WebMvcConfigurerAdapter and overriding the
addResourceHandlers method.
I don't think this is configurable through a property file or something similar, you'll have to write some code. See the answer to this question.

Related

Serve a React .net core template from subdomain

I'm trying to serve a .net core (5.03) web app with the React template from a subdomain, meaning it should serve the static assets from https://someServer/someSite and not from https://someServer, like the Web Server (IIS10) is doing right now after being pointed to the directory.
It serves the index.html file from the right place, But tries to get the other assets and calls from the main domain.
I tried to directly edit the <base> element, but to no use.
How do I configure what path should I serve from without ejecting the CRA and directly editing the webpack.config?
Turns out you have to change %APP_PATH% env var in the CRA, or add an homePage property in your package.json (inside the ClientApp).
The settings in Startup.cs are already relative to the DLL path.

Cannot access pages with direct url after building project for deployment Spring and React

When running my spring app from my IDE and running the React app from within VSCode, everything worked perfectly. I used the build script to build my React project, and then put the output into my /static folder of Spring. Then I used mvn clean install to build the .jar file. After running the entire app from the .jar file, I can access my homepage with localhost:5000. I can also use my navbar links to access different parts of the website, like the Home page and the About page... But if I try to manually enter the url localhost:5000/about I get a 404 Not found error.. What am I doing wrong?
My guess is that your Spring (webmvc?) application is not configured to listen to different URLs other than /. And while it may seem as if the navbar successfully redirects to http://localhost:5000/about, in reality the single page application uses JavaScript client-side routing to change the URL in the browser, unload the currently rendered page, and load another page.
If you are indeed using Spring MVC, you could (among other options) modify your Spring static resource configuration, modify your #RequestMapping to listen to multiple endpoints, or use a ViewControllerRegistry.

Managing routes in reactjs app in production

How is routing handled in a built react app?
Specifically, in a development environment, we can simply hit <host>:<port>/<some-path> and the corresponding component is loaded, but once the app is built, we get a bunch of static files and single index.html file, which are then served by some server.
Now, upon hitting the url <server-host>:<server-port>, the app works as intended, but upon entering the path, say <server-host>:<server-port>/<component-path>, a 404 error is returned.
If there is, say a button, upon clicking which, the same /<component-path> is to be redirected, the app works, but then again upon refreshing that page, 404 error occurs.
How can this be solved? What is the correct way to serve such apps having many components at different routes?
approach1:(recommended)
In server config you should point all urls ( http://ipaddress:port/<* any url pattern>) to index.html of react-app . this is known as fallback-mechanism.
And when any request comes,index.html of React app will take care of that automatically because it is single page application.
approach2:
Use HashRouter in React app. So You will not have to configure anything.
Depending on which server you are deploying to, you should redirect all errors to the index.html look for the configuration maybe htaccess or for example if it an AWS S3 bucket you just specify the error page to the same index.html file that is served. Then you handle actual error in your code using a routing library like maybe react-router-dom to take care of actual error. Your failure is because in normal circumstances in a static host when you provide a URL like <server-port>/<component-path> the assumption the server makes is that there is a folder with name component-path in your root directory which has an index file from where to load and display but in the case of React single page application, everything is managed by the index.html. So every request has to pass via the index.html

How to redirect crawlers requests to pre-rendered pages when using Amazon S3?

Problem
I have a static SPA site built with Angular and hosted on Amazon S3. I'm trying to make my pre-rendered pages accessible by crawlers, but I can't redirect the crawlers requests since Amazon S3 does not offer a URL Rewrite option and the Redirect rules are limited.
What I have
I've added the following meta-tag to the <head> of my index.html page:
<meta name="fragment" content="!">
Also, my SPA is using pretty URLs (without the hash # sign) with HTML5 push state.
With this setup, when a crawler finds my http://mywebsite.com/about link, it will make a GET request to http://mywebsite.com/about?_escaped_fragment_=. This is a pattern defined by Google and followed by others crawlers.
What I need is to answer this request with a pre-rendered version of the about.html file. I've already done this pre-rendering with Phantom.js, but I can't serve the correct file to crawlers because Amazon S3 do not have a rewrite rule.
In a nginx server, the solution would be to add a rewrite rule like:
location / {
if ($args ~ "_escaped_fragment_=") {
rewrite ^/(.*)$ /snapshots/$1.html break;
}
}
But in Amazon S3, I'm limited by their redirect rules based on KeyPrefixes and HttpErrorCodes. The ?_escaped_fragment_= is not a KeyPrefix, since it appears at the end of the URL, and it gives no HTTP error since Angular will ignore it.
What I've tried
I've started trying using dynamic templates with ngRoute, but later I've realized that I can't solve this with any Angular solution since I'm targeting crawlers that can't execute JavaScript.
With Amazon S3, I have to stick with their redirect rules.
I've managed to get it working with an ugly workaround. If I create a new rule for each page, I'm done:
<RoutingRules>
<!-- each page needs it own rule -->
<RoutingRule>
<Condition>
<KeyPrefixEquals>about?_escaped_fragment_=</KeyPrefixEquals>
</Condition>
<Redirect>
<HostName>mywebsite.com</HostName>
<ReplaceKeyPrefixWith>snapshots/about.html</ReplaceKeyPrefixWith>
</Redirect>
</RoutingRule>
</RoutingRules>
As you can see in this solution, each page will need its own rule. Since Amazon limits to only 50 redirect rules, this is not a viable solution.
Another solution would be to forget about pretty URLs and use hashbangs. With this, my link would be http://mywebsite.com/#!about and crawlers would request this with http://mywebsite.com/?_escaped_fragment_=about. Since the URL will start with ?_escaped_fragment_=, it can be captured with the KeyPrefix and just one redirect rule would be enough. However, I don't want to use ugly URLs.
So, how can I have a static SPA in Amazon S3 and be SEO-friendly?
Short Answer
Amazon S3 (and Amazon CloudFront) does not offer rewrite rules and have only limited redirect options. However, you don't need to redirect or rewrite your URL requests. Just pre-render all HTML files and upload them following your website paths.
Since a user browsing the webpage has JavaScript enabled, Angular will be triggered and will take control over the page which results into a re-rendering of the template. With this, all Angular functionalities will be available for this user.
Regarding the crawler, the pre-rendered page will be enough.
Example
If you have a website named www.myblog.com and a link to another page with the URL www.myblog.com/posts/my-first-post. Probably, your Angular app has the following structure: an index.html file that is in your root directory and is responsible for everything. The page my-first-post is a partial HTML file located in /partials/my-first-post.html.
The solution in this case is to use a pre-rendering tool at deploy time. You can use PhantomJS for this, but you can't use a middleware tool like Prerender because you have a static site hosted in Amazon S3.
You need to use this pre-render tool to create two files: index.html and my-first-post. Note that my-first-post will be an HTML file without the .html extension, but you will need to set its Content-Type to text/html when you upload to Amazon S3.
You will place the index.html file in your root directory and my-first-post inside a folder named posts to match your URL path /posts/my-first-post.
With this approach, the crawler will be able to retrieve your HTML file and the user will be happy to use all Angular functionalities.
Note: this solution requires that all files be referenced using the root path. Relative paths will not work if you visit the link www.myblog.com/posts/my-first-post.
By root path, I mean:
<script src="/js/myfile.js"></script>
The wrong way, using relative paths, would be:
<script src="js/myfile.js"></script>
EDIT:
Below follows a small JavaScript code that I've used to prerender pages using PhantomJS. After installing PhantomJS and testing the script with a single page, add to your build process a script to prerender all pages before deploying your site.
var fs = require('fs');
var webPage = require('webpage');
var page = webPage.create();
// since this tool will run before your production deploy,
// your target URL will be your dev/staging environment (localhost, in this example)
var path = 'pages/my-page';
var url = 'http://localhost/' + path;
page.open(url, function (status) {
if (status != 'success')
throw 'Error trying to prerender ' + url;
var content = page.content;
fs.write(path, content, 'w');
console.log("The file was saved.");
phantom.exit();
});
Note: it looks like Node.js, but it isn't. It must be executed with Phantom executable and not Node.

Configure Amazon S3 static site with Angular JS ui.router html5Mode(true) on page refresh

How can I configure an Amazon S3 static webpage to properly route Angular ui.router html5Mode routes? On page refresh, it will make a request for a file that doesn't exist, and angular can't handle it. In the docs, they recommend changing your URL rewrites on the server.
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
However, S3 is storage, and doesn't offer the same redirection options
I have been trying to use the built in redirection rules such as
<RoutingRules>
<RoutingRule>
<Condition>
<HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals >
</Condition>
<Redirect>
<HostName>[[ your application's domain name ]]</HostName>
<ReplaceKeyPrefixWith>#/</ReplaceKeyPrefixWith>
</Redirect>
</RoutingRule>
</RoutingRules>
However, this just leads to a redirect loop.
Any suggestions?
In the Frequently Asked Questions, they rewrite almost everything to serve the index.html page. For HTML5 fallback mode you need to use #!/ (hashbang).
You could change this:
<ReplaceKeyPrefixWith>#/</ReplaceKeyPrefixWith>
with
<ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith>
More details on this answer: https://stackoverflow.com/a/16877231/1733117
You may also need to configure your app for using that prefix:
angular.module(...)
...
.config(function($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
})
Make sure you have the index route configured for your website. Mostly it is index.html
Remove routing rules from S3 configurations
Put a Cloudfront in front of your S3 bucket.
Configure error page rules for your Cloudfront instance.
In the error rules specify:
Http error code: 404 (and 403 or other errors as per need)
Error Caching Minimum TTL (seconds) : 0
Customize response: Yes
Response Page Path : /index.html
HTTP Response Code: 200
Basically there are 3 options, use an EC2 instance to perform the actual server rewrites to the configured HTML5 routes, or, like dnozay suggested, use the fallback mode and re-write requests to use the #! hashbang. Finally, you could just use the standard angular routes, which is the option I went with. Less hassle, and when Angular 2.0 rolls around, you can update to that.
https://stackoverflow.com/a/16877231/1733117
Doesn't really address the routing issue here.
here is another option using nginx proxy_pass, it also allows you to have multiple projects in subfolders and use subdomains
S3 Static Website Hosting Route All Paths to Index.html

Resources