So I'm trying to use angular routing for my project but it seems that only one route is working properly. I can access any of the routes if I used 'localhost/#/{{routeName}}' but everything except home returns a 404 error when I use the format 'localhost/{{routeName}}'. Here's my config
angular.module('shasta-water', ['search', 'ngRoute']).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
redirectTo: '/home'
})
.when('/home', {
templateUrl: 'Templates/HomeTemplate.html'
})
.when('/search', {
templateUrl: 'Templates/SearchTemplate.html',
controller: 'searchCtrl'
})
.when('/add', {
templateUrl: 'Templates/AddTemplate.html'
})
.otherwise({
// templateUrl: 'Templates/ErrorTemplate.html'
redirectTo: '/home'
});
}]);
You'll need to make sure the server also knows what do with these urls it receives requests for when you use HTML5 mode (without #) you can do this by:
Apache/PHP
Inside your .htaccess file in your root folder. Handle routes in index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) /index.php [NC,L]
From: https://stackoverflow.com/a/22740184/5171528
ASP.NET
<!-- from https://stackoverflow.com/questions/25916851/wrapping-staticfilemiddleware-to-redirect-404-errors -->
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<rewrite>
<rules>
<!--Redirect selected traffic to index -->
<rule name="Index Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_URI}" matchType="Pattern" pattern="^/api/" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Related
I serve react SPA through IIS. (uploaded build results in specific directory)
Accessing url http://example.com/About directly or refresh returned 404 error, so I figured out to add web.config like below.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="React Routes" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Previous problem is solved, but I still cannot access nested urls like http://example.com/directory/page1 directly. (Page does not return any error codes, just blank!)
Are there any missing points?
Thanks in advance.
I had the same problem and eventually realized that the web.config is good, but the problem were the relative paths to JS bundles in my index.html.
For example, a script tag in your index.html might be something like:
<script defer="defer" src="app.js"></script>
If you visit http://example.com/directory/page1, IIS actually returns your index.html but the HTML contains relative src paths, so it tries to load the JS bundle at http://example.com/directory/app.js, which does not exist.
I fixed the issue by setting the output public path in my webpack config output: { publicPath: '/' } which makes the src an absolute path:
<script defer="defer" src="/app.js"></script>
https://webpack.js.org/configuration/output/#outputpublicpath
I have developed angular js web application and hosted in IIS server. My web app is developed only by using javascript, css and html.
I am trying to implement Prerender.io in my application. I configured all the required necessary steps including
1 - Added fragment
<head>
<meta name="fragment" content"!">
<meta property="og:title" content="{{header.metaservice.metaTitle()}}" />
<meta name="description" property="og:description" content="{{header.metaservice.metaDescription()}}" />
</head>
2 - Added custom header
<httpProtocol>
<customHeaders>
<add name="X-Prerender-Token" value="XXXX" />
</customHeaders>
</httpProtocol>
3 - Defined rewrite rule
<rewrite>
<rules>
<rule name="Seo rewrite rule" stopProcessing="true">
<match url="^(?!.*?(\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.m4v|\.torrent))(.*)" ignoreCase="false" />
<serverVariables>
<set name="HTTP_X_PRERENDER_TOKEN" value="XXX" />
</serverVariables>
<conditions>
<add input="{QUERY_STRING}" pattern="(.*)_escaped_fragment_(.*)" ignoreCase="false" />
</conditions>
<action type="Rewrite" url="http://service.prerender.io/https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
</rule>
</rules>
</rewrite>
4 - Installs ARR in which i enable the proxy
However, even though I have included all the necessary steps, when I paste my link,it is showing me something like this:
How to host server side rendering application which developed in react js. Now I want to deployed in IIS. So, how can I achieve this.
anyone suggest any example.
Please help me.
You still need to have node.js on your server. IIS will just proxy your app.
There is different ways how to achieve that:
With IISNode project:
Instructions you can find here:
http://www.amazedsaint.com/2011/09/creating-10-minute-todo-listing-app-on.html
With ARR(Application Request Routing) module for IIS:
Instructions you can find here: https://adamtuttle.codes/blog/2015/add-node-to-existing-iis-server/
Install IIS node:
x64 - [https://github.com/azure/iisnode/releases/download/v0.2.21/iisnode-full-v0.2.21-x64.msi)
Install URL rewrite module.
Create Web.config with following declarations in <configuration>/<system.webServer>:
<handlers>
<add name="iisnode" path="server.js" verb="*" modules="iisnode" />
</handlers>
<rewrite>
<rules>
<rule name="Server-side rendering" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
</conditions>
<action type="Rewrite" url="server.js" />
</rule>
</rules>
You can optionally exclude node_modules so they are not served by IIS:
<security>
<requestFiltering>
<hiddenSegments>
<add segment="node_modules" />
</hiddenSegments>
</requestFiltering>
</security>
Create node.js server, for example with express.js:
import express from 'express'
const app = express()
app.get('*', (req, res) => {
/render app here/
});
app.listen(process.env.PORT);
Remember to bind to process.env.PORT as it is passed to your server by the IIS!
Render your app server side, for example like this:
const App = ({message}) => <div>Hello {message}</div>
const template = ...
(StackOverflow eats my tags embedded in js... so copy that and use string interpolation)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<div id="app">${body}</div>
</body>
<script async src="/bundle.js"></script>
</html>
import { renderToString } from 'react-dom/server'
const renderedComponent = renderToString(<App message={`from ${req.url}`} /> )
const html = template(renderedComponent)
res.send(html)
Configure your build tool and router.
You can create two separate build targets for the Webpack - one for the client and one for the server. You should also handle in-app routing but that depends on what library you are using.
var app = angular.module("myApp", ["ngRoute","ui.router"]);
app.config(function($routeProvider,$urlRouterProvider,$locationProvider,$provide, $stateProvider) {
$routeProvider
.when("/", {
templateUrl : "templates/main.htm"
})
.when("/london", {
templateUrl : "templates/london.htm",
controller:"ctrl"
})
.when("/paris", {
templateUrl : "templates/paris.htm"
});
$locationProvider.html5Mode(true);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap Example</title>
<base href="/simpleAnjularjs/" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body ng-app="myApp">
<!-- routeProvider -->
Red
Green
<div ng-view></div>
<!-- stateProvider -->
<!-- <a ui-sref="red">Red</a>
<a ui-sref="green">Green</a>
<div ui-view></div> -->
<!-- <script src="js/angular.min.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script> -->
<script src="node_modules/angular-route/angular-route.js"></script>
<script src="js/Angularjs_ui_routing.js"></script>
<script src="app.js"></script>
</body>
</html>
where other templates(london.html,paris.html,main.html) used are normal html pages with a default tag and when i reload any of the pages i'm getting an error saying "The requested URL /simpleAnjularjs/paris was not found on this server"
How to: Configure your server to work with html5Mode
When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites.
Apache Rewrites
<VirtualHost *:80>
ServerName my-app
DocumentRoot /path/to/app
<Directory /path/to/app>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
Azure IIS Rewrites
<system.webServer>
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
I do not understand why my routes are not working except when I remove the "/" at the beginning.
Here's my routes:
app.config(function($locationProvider, $routeProvider)
{
$locationProvider.html5Mode(true);
$routeProvider
.when('/', { templateUrl: 'templates/views/home.html', controller: 'HomeController' })
.when('/about', { templateUrl: 'templates/views/about.html', controller: 'AboutController' })
.when('/contact', { templateUrl: 'templates/views/contact.html', controller: 'ContactController' })
.otherwise({ redirectTo: '/404' });
});
and my html look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/angular/">
<meta charset="utf-8">
<title>AngularJS Demo</title>
<link rel="stylesheet" href="css/app.css">
</head>
<body ng-cloak ng-app="app">
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<div ng-view></div>
<script src="js/libs.js"></script>
<script src="js/app.js"></script>
</body>
</html>
So if I go to
http://example.com/angular/
everything goes as excepted but if i click on the "Contact" link, it will bring me to
http://example.com/contact
instead of
http://example.com/angular/contact
Any idea what is going wrong with my code?
P.S. I also have the following .htaccess
RewriteEngine On
Options FollowSymLinks
RewriteBase /angular/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.html [QSA,NC,L]
Thanks
Yes of course, here it is:
Let me know if you need anything else. Please note that this is the content of my "angular folder", which is at the root of my server "public_html" root.
Thanks