Why my angular app sometime show 404 error? - html

I have a site deployed using github page and sometime i get a 404 error, this also happend in localhost using ng serve --open
If you try to go on this page for the first time, you may have a 404 error : https://maximegillot.github.io/formation/kafka
But if you go to home page : https://maximegillot.github.io/ and manualy navigate to /formation/kafka you probably wont have any problems ...
I also have this problem when my site is deployed using ng serve --open
I feel like this problem is random and i dont know where to start investigating.
To deploy i just use ng build --aot --vendor-chunk --common-chunk --delete-output-path --build-optimizer and publish /dist/mgi-site/* on github : https://github.com/MaximeGillot/MaximeGillot.github.io
my index.html
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gillot Maxime</title>
<base href="/">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"/>
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet"
type="text/css"/>
<link rel="icon" type="image/x-icon" href="assets/favicon.ico"/>
<script src="https://use.fontawesome.com/releases/v5.15.3/js/all.js" crossorigin="anonymous">
...
</head>
<body>
<app-root></app-root>
</body>
</html>
file app-routing.module.ts :
const routes: Routes = [
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: 'formation/nifi', component: FormationNifiComponent},
{path: 'formation/kafka', component: FormationKafkaComponent},
{path: 'home', component: MainComponent},
{path: 'cv', component: CvComponent},
{path: 'projets', component: ProjetComponent}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}

Angular is a single page application and when deployed without using the #, the hosting site tries to find the path locally as a folder path which doesn't exist and the reason why you get the 404 error.
If you don't have one already, you will need a web.config file set up to handle the redirects.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Angular Routes" 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="./index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
SOURCES:
https://angular.io/guide/deployment#server-configuration
https://indepth.dev/posts/1239/deploy-an-angular-application-to-iis

Related

Page linking not working in angular build on domain [duplicate]

This question already has answers here:
Angular routing not working on Netlify on page refresh
(5 answers)
Closed 4 years ago.
When clicking any links within my website on my serve of it, they work. However, after using ng build, none of the page links work. The website is: hiphost.co.za if you would like to test it yourself and see.
here is the code for my router:
RouterModule.forRoot([
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: 'home',
component: HomeComponent,
pathMatch: 'full'
},
{
path: 'terms-and-conditions',
component: TermsAndConditionsComponent
},
{
path: 'privacy',
component: PrivacyPolicyComponent
},
{
path: 'about',
component: AboutComponent
},
{
path: 'contact',
component: ContactComponent
},
{
path: 'team',
component: TeamComponent
},
{
path:'safety',
component: SafetyComponent
}
]
)
So when you go to hiphost, it automatically redirects to /home, and then no links from there will work
All the request of routing is being handled by server instead of your app thus giving 404.
Easiest solution of it will be to direct your server to redirect all your requests to index.html so that your angular router can handle it.
In production, angular apps are hosted by a web server. SO when you are redirecting to any nested view. the web server does not recognize the path & throws 404 error.
Kindly follow this link to know how to tell web server to navigate to the nested view.
Rewriting URL for angular app in production
you need this on your web.config file
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS 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>
you also need to add this on your index.html.
<base href="/">

Use google maps javascript api on my cordova project

I want to use google maps javascript api on my cordova project. I noticed by a lot of search to need to implement white list policy in config.xml. But I can't understand what to implement in config.xml. Please help. Followings are my codes and trial result.
---config.xml---
<?xml version='1.0' encoding='utf-8'?>
<widget id="net.thinctank.onmap" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>Map</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<author email="dev#cordova.apache.org" href="http://cordova.io">
Apache Cordova Team
</author>
<content src="index.html" />
<plugin name="cordova-plugin-whitelist" spec="1" />
<access origin="https://maps.googleapis.com/maps/api/js?key=MYKEY" />
<allow-navigation href="https://maps.googleapis.com/maps/api/js?key=MYKEY" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<platform name="android">
<allow-intent href="market:*" />
</platform>
<platform name="ios">
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
</platform>
</widget>
---index.html---
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
---index.js---
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
this.receivedEvent('deviceready');
},
receivedEvent: function(id) {
console.log('Received Event: ' + id);
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
}
};
app.initialize();
I tried to execute by "cordova serve android" command but i got the error↓
"Refused to load the script 'https://maps.googleapis.com/maps/api/js?key=MYKEY' because it violates the following Content Security Policy directive: "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback."

ServiceStack not rendering Razor Views. Just seeing Snapshot. Config wrong?

Note: This question while similar to this one however it's about different issues.
It seems for whatever reason ServiceStack is not running/compiling Razor views and seems like a config issue however RazorRockstarts runs fine.
I'm using ServiceStack 4.0.11 and have compared against RazorRockstars runnning ServiceStack 4.0.8
In VS2013 I have created a new ASP.NET Website (Empty)
Install-Package ServiceStack
Install-Package ServiceStack.Razor
Added httpHandlers to web.config
Created AppHost and .Init() in Global.asax Application_Start.
AppHost.LoadPlugin(new RazorFormat());
Created /Services/HomeService.cs (inherited from ServiceStack.Service)
Created Home route in HomeService
Created /Views/Home/Home.cshtml
I run in debug on VS 2013 and all I get is the ServiceStack snapshot when going to /home. What am I missing?
/AppHost.cs
using Funq;
using ServiceStack;
using ServiceStack.Razor;
namespace SSTest
{
public class AppHost : AppHostBase
{
public AppHost() : base("SSTest", typeof(AppHost).Assembly) { }
public override void Configure(Container container)
{
LoadPlugin(new RazorFormat());
}
public static void Start()
{
new AppHost().Init();
}
}
}
/Global.asax
protected void Application_Start(object sender, EventArgs e)
{
AppHost.Start();
}
/Services/HomeService.cs
using ServiceStack;
namespace SSTest.Services
{
[Route("/home")]
public class Home
{
public string Name { get; set; }
}
[DefaultView("Home")]
public class HomeServices : Service
{
public object Get(Home request)
{
return new Home(){Name = "Here's home!"};
}
}
}
/Views/Home/Home.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Home</title>
</head>
<body>
<div>
<h1>This is home!!</h1>
</div>
</body>
</html>
/Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web>
<httpHandlers>
<add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
<buildProviders>
<add extension=".cshtml" type="ServiceStack.Razor.CSharpRazorBuildProvider, ServiceStack.Razor" />
</buildProviders>
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<!-- Required for IIS 7.0 -->
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>
<appSettings>
<add key="webPages:Enabled" value="false" />
</appSettings>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="ServiceStack.Razor.ViewPage">
<namespaces>
<add namespace="ServiceStack" />
<add namespace="ServiceStack.Html" />
<add namespace="ServiceStack.Razor" />
<add namespace="ServiceStack.Text" />
<add namespace="ServiceStack.OrmLite" />
<add namespace="SSTest" />
<add namespace="SSTest.Services" />
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
I know mythz has solved your problem, but something else to check for future readers with the same problem:
Make sure your *.cshtml files are copied to the output directory. For whatever reason, mine weren't, thus ServiceStack couldn't find them and all I got was the snapshot like yourself.
I'm not sure if this is related to using a self-hosted console application instead of a web project.
Inside Configure() plugins should be loaded with:
Plugins.Add(new RazorFormat());
In ServiceStack.Razor Layout = null, suggests to use the default layout template Views\_Layout.cshtml, you can choose not use any template with Layout="" instead.
If you don't have OrmLite installed then you want to remove the ServiceStack.OrmLite namespace from being included in all Razor pages by removing it from your Web.config:
<add namespace="ServiceStack.OrmLite" />
Your view should be located in /Views/Home.cshtml instead of /Views/Home/Home.cshtml.
I was having the exact same issue! With the current ServiceStack VS template (as of April 1, 2015 and no this isn't an April Fools joke!), the following line will mess things up if you're running a self-hosted service:
WebHostPhysicalPath = Path.GetFullPath(Path.Combine("~".MapServerPath(), "..", "..")),
This is within your AppHost.cs file inside of the Configure(Container) function within the SetConfig(new HostConfig { /* ... here ... */ } ); block.
Comment out the entire WebHostPhysicalPath = ... line and re-run your application.
A better fix than simply commenting it out is to set the correct directory which is either your actual bin directory via:
WebHostPhysicalPath = Path.GetFullPath("~".MapServerPath()),
Or, if you have a specific build architecture (ie. x86 or x64 instead of AnyCPU), you likely have a third layer of folders. So change the WebHostPhysicalPath to this:
WebHostPhysicalPath = Path.GetFullPath(Path.Combine("~".MapServerPath(), "..", "..", "..")),

HTTP 404 when linking dojo/dojo.js script src in Spring MVC

Ok, so I've been stuck trying to setup a Spring MVC project integrated with DOJO for some time now. Finally decided it was time to make an account here and ask the question. I have everything loading except for my dojo.js file that I am referencing from my tag. I'll provide my project hierarchy and what I'm seeing:
My #RequestMapping method.
#RequestMapping(value = "/rbd", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
..When I browse to http://localhost:8080/myproject/rbd the application is successfully loading the home.jsp file, which is shown below:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# page session="false"%>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
<link rel="icon" href="../sba-icon.png" type="image/x-icon" />
<link rel="shortcut icon" href="../sba-icon.png" type="image/x-icon" />
<script src="<spring:url value='/scripts/dojo/dojo.js'/>" data-dojo-config:"locale:'en', async:true, parseOnLoad:false"></script>
..My JBOSS deployments folder follows the hierarchy myproject/scripts/dojo/dojo.js. My home.jsp is in myproject/WEB-INF/views/home.jsp. Is the location of the src tag relative to the location of the home.jsp? I'm so lost because I keep getting 404 errors.. yet I obviously know that dojo.js is on the server. I've tried every path that makes sense to me, I am a Spring/MVC beginner, so don't bash please!
Thanks for the help! :)
EDIT: Here is my init of my DispatcherServlet within my web.xml ...
<servlet>
<servlet-name>rbd</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/rbd/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rbd</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
..And here is my servlet-context.xml located in the path shown above..
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
The problem is that you have no mapping to your /scripts directory. When using Spring MVC, each request is being mapped to something. You have mapped the following:
/rbd: In your controller
/resources: In your servlet-context.xml (as a resource)
As you can see there's no kind of mapping for the /scripts directory, so in order to make it work you should either move it to the resources-folder (and adjust the links) or provide some additional mapping, by adding the following to your configuration:
<resources mapping="/scripts/**" location="/scripts/" />
Without it Spring simply doesn't know where it should refer to when you're trying to access Dojo.
DispatcherServlet intercepts the js file
you should set <servlet-mapping> like:
<servlet-mapping>
<servlet-name>rbd</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
meanwhile change your controller mapping:
#RequestMapping(value = "/rbd.do", method = RequestMethod.GET)

Google Apps Script-How to get value from XmlDocument?

I am trying to get all calender details of all users. I got this successfully but its return result in Xml format as following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<id>http://www.google.com/calendar/feeds/email-id/private/full</id>
<updated>2012-02-15T15:34:49.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/g/2005#event"/>
<title type="text">email-id</title>
<subtitle type="text">email-id</subtitle>
<link href="https://www.google.com/calendar/embed?src=email-id" rel="alternate" type="text/html"/>
<link href="https://www.google.com/calendar/feeds/email-id/private/full" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
<link href="https://www.google.com/calendar/feeds/email-id/private/full" rel="http://schemas.google.com/g/2005#post" type="application/atom+xml"/>
<link href="https://www.google.com/calendar/feeds/email-id/private/full/batch" rel="http://schemas.google.com/g/2005#batch" type="application/atom+xml"/>
<link href="https://www.google.com/calendar/feeds/email-id/private/full?max-results=25" rel="self" type="application/atom+xml"/>
<author>
<name>Name</name>
<email>email-id</email>
</author>
<generator uri="http://www.google.com/calendar" version="1.0">Google Calendar</generator>
<openSearch:totalResults xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">1</openSearch:totalResults>
<openSearch:startIndex xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">1</openSearch:startIndex>
<openSearch:itemsPerPage xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">25</openSearch:itemsPerPage>
<gCal:timezone value="Europe/Dublin" xmlns:gCal="http://schemas.google.com/gCal/2005"/>
<gCal:timesCleaned value="0" xmlns:gCal="http://schemas.google.com/gCal/2005"/>
<entry>
<id>http://www.google.com/calendar/feeds/email-id/private/full/vj39u2qedgphrp10nah92h6ho0</id>
<published>2012-02-15T11:21:54.000Z</published>
<updated>2012-02-15T11:21:54.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/g/2005#event"/>
<title type="text">Test Appointment</title>
<content type="text">This is a test description</content>
<link href="https://www.google.com/calendar/event?eid=dmozOXUycWVkZ3BocnAxMG5haDkyaDZobzAgcmFoaW1AZGFtc2" rel="alternate" title="alternate" type="text/html"/>
...
</entry>
</feed>
I want to get the value of title and content.Please share me with the solution
Thank you
Use the built-in Xml service https://developers.google.com/apps-script/service_xml.
With this sevice you can parse thru the xml document.