I am trying to build simple routing app in angularjs. I have main index.html page with ng-view div and javascript code for routing. Also 2 simple html pages view2.html and view3.html placed in sub folder partials1.
I am getting below error. Please help.
Error: Access is denied.
Error: [$compile:tpload] Failed to load template: partials1/view3.html
http://errors.angularjs.org/1.3.15/$compile/tpload?p0=partials1%2Fview3.html
index.html:
<div data-ng-view></div>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script type="text/javascript">
var demoApp = angular.module('demoApp', [ 'ngRoute' ]);
demoApp.controller('SimpleController', function($scope) {
$scope.customers = [ {
name : 'Jon Smith1',
city : 'Charlotte'
}, {
name : 'John Doe',
city : 'New York'
}, {
name : 'Jane Doe',
city : 'Jacksonville'
} ];
});
demoApp.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl : 'partials1/view3.html',
controller : 'SimpleController'
}).when('/view2', {
templateUrl : 'partials1/view2.html',
controller : 'SimpleController'
}).otherwise({
redirectTo : '/view1'
});
} ]);
</script>
view2.html
<div class="container">33333333333333</div>
view3.html
<div class="container">33333333333333</div>
Error: Access is denied tells you that the template is not accessible. Try to open the template in your browser. Something like this: http://my_project/partials1/view3.html. To see the full URL which is used by your app, use a dubug console (XHR tab).
Error: [$compile:tpload] Failed to load template: xyz.html (HTTP status: 404 Not Found)
can be caused by below setting in web.config
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
This causes to block any direct request to the file in Views directory. Angular xhr request to this file is blocked by this.
Comment it out and see if things work. Use this with caution as it allows access to your files.
You can also check on this url for more responses: Error: $compile:tpload failed to load template Http status : 404
In my case, the issue is that I added Default Headers such as Accept = 'application/json'. So my routes suddenly stopped working, because those headers were not only applied to my $http.post calls, they were also applied to my Routing... ? Weird.
I had the same error, in my case the web server was written with node js and the uri to get views that were in the specified path with $stateProvider was not created, since for each view/template that is wanted to display an http request of type Xhr GET is made.
As the uri did not exist I obtained a 404 code and this made the browser got into callback that killed him. Make sure your server is returning the requested view. (Translated with google translate)
Related
The current behavior:
Service worker does not register due to the below error
The expected behavior:
Service worker registers
Details
Posted as a github issue:
https://github.com/facebook/create-react-app/issues/8593
Service worker is giving the following error when attempting to register:
Error during service worker registration:
DOMException: Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/sw.js'):
The script has an unsupported MIME type ('text/html').
console. # index.js:1
sw.js is showing in the sources tab of the Chrome dev tools, but not registering.
React version: 16.12.0
Error Message:
Error during service worker registration: DOMException:
Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/sw.js'):
The script has an unsupported MIME type ('text/html').
Failed ServiceWorker in Chrome's Inspect Tab:
Steps To Reproduce:
Register a Service Worker in React (change from unregister to register, or place SW code directly in index.html, or use a simpler SW. All cause the same error when running, in either dev or a build react app.)
SW Example:
export function register() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./sw.js")
.then(function(registration) {
// Successful registration
console.log(
"Hooray. Registration successful, scope is:",
registration.scope
);
})
.catch(function(error) {
// Failed registration, service worker won’t be installed
console.log(
"Whoops. Service worker registration failed, error:",
error
);
});
}
}
Also, `http://localhost:3000/sw.js when using the default SW from React returns this HTML:
Using the code sample above returns index.html (default 404, http://localhost:3000/) when trying to access http://localhost:3000/sw.js
Suggested fixes:
Move sw.js to public folder, gives this error:
Is there a way to change the header (from text/html to application/javascript) for specifically sw.js when served to the browser in React?
I tried following some Medium articles on registering custom serviceWorkers in React, to no avail...
When running webpack dev server, it renders default index.html for missing resource.
If you use your browser to load http://localhost:3000/sw.js, you will actually see a rendered react app (started by the index.html). That's why the mime type is html, not javascript.
This fallback to index.html is designed to support SPA with front-end routes. For example /product/123/reviews has no such html file in backend, the JS SPA app takes care of it in front-end.
Why your file is missing? I guess you created that file in the root folder of your project.
Webpack dev server doesn't serve from that root folder.
Move your sw.js into public/ folder of your project, it will be served up as expected.
This may be a duplicate of this one 61776698
Main thing you need to know: Create the serviceWorker inside public folder in order to be treated as .js file and not text/html file.
Then register that service in your index.js
Step 1, create public/sw.js
self.addEventListener('message', async (event) => {
console.log('Got message in the service worker', event);
});
Step 2, create src/sw-register.js
export default function LocalServiceWorkerRegister() {
const swPath = `${process.env.PUBLIC_URL}/sw-build.js`;
if ('serviceWorker' in navigator && process.env.NODE_ENV !== 'production') {
window.addEventListener('load', function () {
navigator.serviceWorker.register(swPath).then(registration => {
console.log('Service worker registered');
});
});
}
}
Step 3, in src/index.js, add these two lines
import LocalServiceWorkerRegister from './sw-register';
...
LocalServiceWorkerRegister();
You can change some things for your needs, but with those changes, you should be able to work with a custom service worker in a create-react-app application
You can write code at server side to handle sw.js file. below is nodejs code which intercept sw.js file request and read from folder and send back to browser.
app.get('/sw.js', (req, res) => {
if (__DEVELOPMENT__) {
http.get('http://localhost:4001/static/build/sw.js', (r) => {
res.set({
'Content-Type': 'text/javascript',
'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate'
});
r.setEncoding('utf8');
r.pipe(res);
}).on('error', (e) => {
console.error(`Error in sending sw.js in dev mode : ${e.message}`);
});
} else {
res.setHeader('Cache-Control', 'max-age=0, no-cache, no-store, must-revalidate');
res.sendFile('sw.js', { root: path.join(__ROOT_DIRECTORY__, 'assets', 'build') }); // eslint-disable-line no-undef
}
});
I am using express and node.js in backend and ejs templating engine in front-end. My app.js look like this
app.get('/book/:id', (req, res)=>{
var book_id = req.params.id;
console.log('this book :', book_id);
Book.findOne({
book_id
}).then((book)=>{
res.render('book.ejs', {book, title: "Book"});
}).catch((e)=>{
// console.log(e);
});
});
book.ejs file
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="books.js"></script>
</head>
<body style="font-family: arial">
<h1><%= title %></h1>
</body>
</html>
But when i route page to book/1234, I got following log in my server
this book : 1234
this book : jquery-3.3.1.min.js
this book : book.js
Why jquery-3.3.1.min.js and book.js are send to book/:id route? I am only sending book/1234 but jquery-3.3.1.min.js and book.js are also sent to server and causing error.
Browser console log is this
GET http://localhost:3000/book/jquery-3.3.1.min.js net::ERR_ABORTED 500 (Internal Server Error)
1234:1 Refused to execute script from 'http://localhost:3000/book/jquery-3.3.1.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
1234:6 GET http://localhost:3000/book/books.js net::ERR_ABORTED 500 (Internal Server Error)
1234:1 Refused to execute script from 'http://localhost:3000/book/books.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Since script links have relative paths, they are loaded from current path, which is /book.
They should either have absolute paths:
<script type="text/javascript" src="/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/books.js"></script>
Or base URL should be specified:
<base href="/">
You are using relative path in src attribute. Since you are serving the page from /books/<id>, if you use a relative path, browser will understand it as /books/(relative_path_of_resource) and so when it comes across those links it is sending a request to books/jquery.js and books/books.js
You should convert your link to point to the correct static path of the js files. Refer this link - https://expressjs.com/en/starter/static-files.html to see how to serve static files and once you set up the serving, you can change the links to /static/books.js and /static/jquery.js
I think that your book.ejs file is under the route of '/book'. if that so, you script tag like <script type="text/javascript" src="books.js"></script> will access the route of /book/book.js ,not your assets.
so you should set you src attribute like this /book.js and make sure you had made your assets accessible.
I have a Polymer webapp deployed using Firebase hosting.
The routing between views works but the error page handling is not.
I have succeeded to reproduce the issue on a minimal example using the official polymer-2-starter-kit example:
https://fir-polymer-404-issue.firebaseapp.com/
For instance, if you open the following URL, the error page is not displayed:
https://fir-polymer-404-issue.firebaseapp.com/not-existing
Instead, I get the error below:
my-not-existing.html:56 Uncaught SyntaxError: Identifier 'baseUrl' has already been declared
at my-not-existing.html:56
(anonymous) # my-not-existing.html:56
The configuration file firebase.json used for the previous example is here:
{
"hosting": {
"public": ".",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
I would like to have the error page handling made by Polymer.
Please note that the same app served by polymer serve works properly.
It seems the problem comes from the Firebase hosting configuration. All traffic is redirected to index.html so when Polymer load a not-existing page, the Firebase server returns an HTTP 200 response. Unfortunately, I have no idea how to fix the problem.
I have tried to create a redirection for non-404 responses only with the following configuration file:
{
"hosting": {
"public": ".",
"redirects": [
{
"source": "**",
"destination": "/index.html",
"type": 200
}
]
}
}
Unfortunately, the type property can be used for 3xx code only:
Error: HTTP Error: 400, hosting.redirects[0].type is not one of enum values: 301,302,303,304,305,307,308
Please also note that a custom 404.html file is placed at the root.
The only solution I see is to list all existing routes (per file) but it looks just crazy.
Any idea is welcome.
The reason neither firebase or polymer is going to handle your 404 page is that when you request a non-existing page, it's not only going to return with the status code 200 but it's also going to return with the HTML of the index page, so it will display something, although that something is really nothing.
Now the way polymer is set up it looks for views in the src folder, so you want a rewrite just on the root and not in the src folder. So change your firebase.json to be
{
"hosting": {
"public": ".",
"rewrites": [{
"source": "/*",
"destination": "/index.html"
}]
}
}
The single * will mean files but not subfolders, this will allow your routeing to work if you enter it in the address bar but if the page is not found the 404 will be handled by polymers routeing. I've set up a firebase application using the polymer starter pack to for an example.
https://testforsoissue.firebaseapp.com/view2
Will work and will take you to view2 as the initial request will be rewritten to return index.html but the request for /src/my-view2.html will not
Whereas a route that is not defined
https://testforsoissue.firebaseapp.com/not-existing
Will throw a 404 (in polymer) as the initial request will again be rewritten to return index.html but the request for /src/my-not-existing.html will not and will happily throw a 404!
P.S. the reason for the error 'baseUrl' has already been declared' is due to the fact the page was using the index.html twice which declares the baseUrl at the top
Edit
If you have subpaths seems like you can use the firebase.json like so
{
"hosting": {
"public": ".",
"rewrites": [{
"source": "!/src/*",
"destination": "/index.html"
}]
}
}
As per documentation, you do not need to do the handling; just create a 404.html:
You can specify a custom 404/Not Found error to be served when a user tries to access a page that does not exist. Simply add a 404.html page to the your project's public directory and the contents of this page will be displayed when Firebase Hosting needs to display a 404 Not Found error to the user.
To avoid the baseUrl error, if you have access to this line of code:
let baseUrl = document.querySelector('base').href;
Try changing it for:
baseUrl = baseUrl || document.querySelector('base').href;
It's not very neat, but it should not complain about the value being defined already.
Although I think this is unrelated to your problem and may stop showing this error once a proper 404 page is defined.
I'm trying to create a single page web application using ng-view but I'm unable to progress. There seems to be a problem loading in the html pages and I don't know what to do about it. Would anybody be able to identify what's wrong with my program?
The following files are contained in a directory called Example:
angular.js (v1.4.3)
angular-route.js (v1.4.3)
script.js
index.html
first.html
second.html
index.html
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="RoutingApp">
<div>
<h2>AngularJS Routing Example</h2>
<p>Jump to the first or second page</p>
<div ng-view></div>
</div>
</body>
</html>
script.js:
var app = angular.module('RoutingApp', ['ngRoute']);
app.config( [ '$routeProvider', function($routeProvider) {
$routeProvider
.when('/first', {
templateUrl: 'first.html'
})
.when('/second', {
templateUrl: 'second.html'
})
.otherwise({
redirectTo: '/'
});
}]);
first.html
<h2>This is the first page.</h2>
second.html
<h2>This is the second page.</h2>
From the Chrome debugging console:
XMLHttpRequest cannot load file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/first.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/first.html'.
at Error (native)
at file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:10514:11
at sendReq (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:10333:9)
at serverRequest (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:10045:16)
at processQueue (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:14567:28)
at file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:14583:27
at Scope.$eval (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:15846:28)
at Scope.$digest (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:15657:31)
at Scope.$apply (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:15951:24)
at HTMLBodyElement.<anonymous> (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:12086:24)(anonymous function) # angular.js:12330 Error: [$compile:tpload] Failed to load template: first.html (HTTP status: undefined undefined)
http://errors.angularjs.org/1.4.3/$compile/tpload?p0=first.html&p1=undefined&p2=undefined
at angular.js:68
at handleError (angular.js:17530)
at processQueue (angular.js:14567)
at angular.js:14583
at Scope.$eval (angular.js:15846)
at Scope.$digest (angular.js:15657)
at Scope.$apply (angular.js:15951)
at HTMLBodyElement.<anonymous> (angular.js:12086)
at HTMLBodyElement.eventHandler (angular.js:3271)
Thanks in advance.
It's because browsers don't allow to access local files through AJAX requests.
You need to serve your page using a web server (e.g. apache) and access the page with http://localhost/index.html
First of all your first or second page</p>
should have links in the following manner
first
also secondly, are you loading your template urls properly, Have a look at this post AngularJS writing an app with no server
I am trying to load json file from server .Here is my services.js file
angular.module('starter.services', [])
/**
* A simple example service that returns some data.
*/
.factory('Friends', function($http) {
var friends;
//here is the code for server access
$http.get('http://wwww.root5solutions.com/ionictest/get.json').then(function(msg){
console.log("console output"+msg.data);
friends=msg.data;
console.log("from server"+friends.data);
});
return {
all: function() {
return friends;
},
get: function(friendId) {
return friends[friendId];
}
}
});
But its not worked properly.Here is my console message
XMLHttpRequest cannot load http://www.root5solutions.com/ionictest/get.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
I have also faced the same problem.I am sure it will resolve your problem,
For Windows... create a Chrome shortcut on your desktop > Right-clic > properties > Shortcut > Edit "target" path : > "C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security
NOTE: After setting this exit from chrome and then open
you have to whitelist that URL
try this
.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
// Allow same origin resource loads.
'self',
// Allow loading from our other assets domain. Note there is a difference between * and **.
'http://wwww.root5solutions.com/ionictest/**',
]);
})
All this problem beacuse i tested only using browser.When tesing on device/emulator its working perfect.There is no need of additional coding to overcome this problem.