Unable to remove # in AngularJS - javascript

The application is making use of the following:
AngularJS (v1.6.4)
webpack
ui-router
One requires the path to be independent of the # in the url.
For this I have added the following in the code:
In app.js
/* in the config section */
$locationProvider.hashPrefix('');
$locationProvider.html5Mode(true);
In index.html
<!-- under the head section -->
<base href="/">
When fired in the below format from address
'http://localhost/pathName'
it gives the following error:
Cannot GET /pathName
But the same works well when accessed through hyperlinks.
Also, on accessing 'http://localhost/#/pathName', the browser modifies the same to 'http://localhost/pathName'.
Is there a way by which the url can be accessed through GET request, by configuring from webpack (or some other way)?
EDIT 1:
Routing Code:
.config(($stateProvider) => {
$stateProvider
.state('pathName', {
url: '/pathName',
template: '<pathNameTemplate />'
});
})

No html5:
user types www.site.com/#/section in browser
request is sent for www.site.com (#... is ignored)
server return index.html
angular launches and see that there is # -- loads specific view
Html5:
user types www.site.com/section in browser
request is sent for www.site.com/section
server return index.html
angular launches and see that there is / -- loads specific view
So server MUST return index.html for all your paths - i.e. this means that you can not make it work from file system (file://.../). You need server and configure it adding redirects
P.S. you do not need this line
$locationProvider.hashPrefix('');

This is sample to remove # from url using
AngularJs v1.5.7
ui-router v0.4.2
web.config
app.js
var app = angular.module("app", ["ui.router"]);
app.config
var config = function (locationProvider) {
locationProvider.html5Mode(true);
}
config.$inject = ["$locationProvider"];
app.config(config);
index.html
<head>
<base href="/" />
</head
If you don't use IIS Service, and use Apache service such as xamp or etc... for your localhost change it to <base href="/sample/" />
web.config
<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>
</rewrite>
Note: you have to add this config because without it, when # removed after refresh [F5] you lose the state.
Remember In Apache (PHP) configs are different, and users have to add the settings in the .htaccess file.

Related

Specifics on How Glassfish Server is Run with IntelliJ Debugger?

I'm curious as to how the IntelliJ debugger uses the domain.xml of my glassfish server and reports a webpage when requested.
Specifically, I have an IntelliJ project called blobGame that uses a Glassfish server that opens a webpage called blobGame when the artifacts .war and .ear are deployed.
Firstly, how are these artifacts deployed? When I deploy them, I MUST have the URL of the localhost be http://localhost:60836/blobGame_war_exploded, and localhost:60836/blobGame DOES NOT WORK, even if I change it in the debug configuration - here is my debugger info
Why is this? Why does the url have to be /blobGame_war_exploded? It cannot even be /blobGame_ear_exploded, as I see that also in the domain.xml.
Here is the snippet of domain.xml for my domain called "domain2":
<applications>
<application object-type="user" name="blobGame_ear_exploded" directory-deployed="true" location="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_ear_exploded/">
<property name="archiveType" value="ear"></property>
<property name="isComposite" value="true"></property>
<property name="appLocation" value="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_ear_exploded/"></property>
<property name="org.glassfish.ejb.container.application_unique_id" value="98074431158681600"></property>
<property name="defaultAppName" value="blobGame_ear_exploded"></property>
<module name="web.war">
<engine sniffer="ejb"></engine>
<engine sniffer="security"></engine>
<engine sniffer="weld"></engine>
<engine sniffer="web"></engine>
</module>
<engine sniffer="ear"></engine>
</application>
<application context-root="/blobGame_war_exploded" object-type="user" name="blobGame_war_exploded" directory-deployed="true" location="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_war_exploded/">
<property name="archiveType" value="war"></property>
<property name="appLocation" value="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_war_exploded/"></property>
<property name="org.glassfish.ejb.container.application_unique_id" value="98074431158812672"></property>
<property name="defaultAppName" value="blobGame_war_exploded"></property>
<module name="blobGame_war_exploded">
<engine sniffer="ejb"></engine>
<engine sniffer="security"></engine>
<engine sniffer="weld"></engine>
<engine sniffer="web"></engine>
</module>
</application>
</applications>
SECOND of all, why does the deployment still use previous artifacts (as I assume they are) when I redeploy or restart the server?
Specifically, when I press restart, I get the exact same HTML and javascript files I was left with before, and even if I edited the html or JS files during the time before my second debug.
(I add alert("test") in the new debug, but it does not show up in the new debug. When I access the index.html page independently the alert does show up).
Here is the index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>keyBoardDemo</title>
</head>
<body>
<canvas id="canvas" width="800" height="600" style="border:1px solid #000000;"></canvas>
<p id="main"></p>
<script type="text/javascript" src=resources.js></script>
<script type="text/javascript" src=canvas.js></script>
<script type="text/javascript" src=keyboard.js></script>
<script type="text/javascript" src=packethandler.js></script>
<script type="text/javascript" src=player.js></script>
<script type="text/javascript" src=websocket.js></script>
</body>
</html>
and here is the canvas.js that it calls:
alert("test 123"); //this is not called on the second redeployment!
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
Firstly, how are these artifacts deployed? When I deploy them, I MUST have the URL ...
By default, IDEA computes context root from the artifact name, by replacing unsupported characters with underscores. Thus, the 'blobGame:war exploded' artifact, by default gets 'blobGame_war_exploded' context root.
To change the context root for the artifact, you may want to open the 'Deployment' tab of the run configuration, check 'Use custom context root' and enter the desired value into the field
'Open browser' field on the 'Server' tab does not affect the server settings, it just allows you to open whatever URL you like after the server start. The field value defaults to the URL computed from the first artifact, but once user have changed it IDEA assumes that user knows better.
Specifically, when I press restart, I get the exact same HTML and javascript files I was left with before, ...
The expected sequence is as follows:
make a change to a resource
update the application on the server with the mentioned 'Update <> application' action: 'Update resource' choice should be enough for an exploded application, redeploy/restart may be needed for archive artifact
reload (refresh) the page, that uses the resource in browser
I suspect you're missing the last (3) step. Please note, step (2) only updates the resource on the server, and to see a change in browser (on client) you should reload the corresponding resources from server by refreshing the page manually.
Hope that helps,
I am going to redirect your second post to this answer

Azure App Service adding '/' in URL

I'm working on a node.js application deployed on Azure App Service.
The application runs as expected on localhost-
http://localhost:55231/search?q=pink+floyd
But when deployed on Azure, the URL acts weird-
http://<appname>.azurewebsites.net/search/?q=pink+floyd Extra '/' before query string.
My Express.js code is-
app.get('/search', function (req, res) {
response = {
search_text:req.query.q,
};
//Few more code
HTML page serving query-
<form action = "/search" method = "GET">
<input type = "text" name = "q" placeholder=" Search your Favourite Music">
<input type = "submit" value = "Search">
</form>
I can't reproduce your issue on Azure App Service with Express. However, the following is what I tried so far.
My folder structure:
My app.js code looks like:
var express = require('express')
var app = express()
app.use(express.static('public'))
app.get('/', function (req, res) {
res.send('Hello Azure!')
})
app.get('/search', function(req, res) {
res.send(200, 'Test')
})
app.listen(process.env.PORT || 3000, function () {
console.log('Example app listening on port 3000!')
})
My test.html code:
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="search" method="GET">
<input type="text" name="q" />
<button type="submit">Search</button>
</form>
</body>
</html>
web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
This configuration file is required if iisnode is used to run node processes behind
IIS or IIS Express. For more information, visit:
https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->
<configuration>
<system.webServer>
<!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
<webSocket enabled="false" />
<handlers>
<!-- Indicates that the app.js file is a node.js site to be handled by the iisnode module -->
<add name="iisnode" path="app.js" verb="*" modules="iisnode"/>
</handlers>
<rewrite>
<rules>
<!-- Do not interfere with requests for node-inspector debugging -->
<rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
<match url="^app.js\/debug[\/]?" />
</rule>
<!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
<rule name="StaticContent">
<action type="Rewrite" url="public{REQUEST_URI}"/>
</rule>
<!-- All other URLs are mapped to the node.js site entry point -->
<rule name="DynamicContent">
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
</conditions>
<action type="Rewrite" url="app.js"/>
</rule>
</rules>
</rewrite>
<!-- bin directory has no special meaning in node.js and apps can be placed in it -->
<security>
<requestFiltering>
<hiddenSegments>
<remove segment="bin"/>
</hiddenSegments>
</requestFiltering>
</security>
<!-- Make sure error responses are left untouched -->
<httpErrors existingResponse="PassThrough" />
<!--
You can control how Node is hosted within IIS using the following options:
* watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
* node_env: will be propagated to node as NODE_ENV environment variable
* debuggingEnabled - controls whether the built-in debugger is enabled
To debug your node.js application:
* set the debuggingEnabled option to "true"
* enable web sockets from the portal at https://manage.windowsazure.com/#Workspaces/WebsiteExtension/Website/aaronexpress/configure
* browse to https://aaronexpress.azurewebsites.net/app.js/debug/
See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
-->
<iisnode watchedFiles="web.config;*.js" debuggingEnabled="false" />
</system.webServer>
</configuration>
Tested result:
And could you share the web.config file which you are using? My guess is you're missing out on a simple thing there.

IIS outboud rule to match the non-existance of substring in file name

I have the following IIS configuration which forces PDFs to be downloaded as files in the browser instead of opening in the browser window.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<outboundRules>
<rule name="Force Download for PDFs" preCondition="FileIsPDF">
<match serverVariable="RESPONSE_Content-Disposition" pattern=".*" />
<conditions>
<add input="{REQUEST_FILENAME}" pattern="(.*)\\([^/]+)\.pdf$" />
</conditions>
<action type="Rewrite" value="attachment; filename={C:2}.pdf" />
</rule>
<preConditions>
<preCondition name="FileIsPDF">
<add input="{REQUEST_FILENAME}" pattern="\.pdf$" />
</preCondition>
</preConditions>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
However I need it to not apply if the file name is xxx_print.pdf, in other words I want the above rule to match all .pdf files except those that have _print at the end of the file name.
How is this possible? Needs to work for IIS7 and above.
Note you may be able to answer this without an understanding of IIS if you know how to use javascript's regular expression to match a string without a particular substring.
Turned out I just had to add another condition to the rule with the negate="true" attribute:
<add input="{REQUEST_FILENAME}" pattern="(.*)\\([^/]+)_print\.pdf$" negate="true" />

Render default image when image not found on server

I have a web page which renders images from a server. If the image is not found, currently the IIS server returns 404 error and hence the image is not rendered.
I have a requirement to put a default image in case the image is not found on the server.
Can I make this setting on the IIS server so that it returns the default image for every invalid image requests?
You can use the javascript onerror() event for images that are not found:
function imgError(image) {
image.onerror = "";
image.src = "somePlaceholderImage.gif";
return true;
}
then your images would be like this:
<img alt="some ALT text" src="http://someurlhere" onerror="imgError(this);">
<rewrite>
<rules>
<rule name="RewriteNoneExist">
<match url="\.(gif|jpe?g|png|bmp)" ignoreCase="true" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
</conditions>
<action type="Rewrite" url="gfx/default.png" />
</rule>
</rules>
</rewrite>

How to remove index.html from url on website based on angularjs

I didn't find a way to remove index.html from the url, because like this looks really ugly.
mydomain.com/index.html#/myview1
mydomain.com/index.html#/myview2
Is there a way to remove that part, like that url will be so clear where the user is.
mydomain.com/myview1
mydomain.com/myview2
Tnx in advance for your time.
Edit:
I just find way that it could work like:
mydomain.com/#/myview1
mydomain.com/#/myview2
which is pretty much better then with index.html.
But still if there is a way for shorter solution let me know.
Maybe this approach could help:
Add $locationProvider.hashPrefix();, which removes index.html in your URL, in your app.js config. Don't forget to add the new dependency. After that your app.js could look similar to this:
angular.module('myApp', [
'ngRoute'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix(); // Removes index.html in URL
$routeProvider.otherwise({redirectTo: '/someroute'});
}]);
Note that this does not remove the hashtag.
You can find your new route at: .../app/#/someroute
activate the html5mode for $location
You'll have to do some work on the server side to set this up. html5mode gets you part of the way, but as soon as the user refreshes, the reference to the file will be wrong. You want links that are persistent and can be shared, presumably. Basically make sure any request to url.com/myapp/{etc} (or whatever) gets redirected to index.html and let your angular app sort out the routing.
Use
<rewrite>
<rules>
<rule name="RewriteRules" 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="/index.html" />
</rule>
</rules>
</rewrite>
And on Index page
<base href="/" />
And on your config use
$locationProvider.html5Mode(true);
It should work

Categories

Resources