I am having a very strange issue, however, i have resolved it but wanted to know why. I am using node.js with express.
In my server.js file i have written route code like:
app.get('/eventname/:event', (req, res) => {
res.render('event.hbs', {
name: req.user.displayName
});
})
There is no specific "eventname" route when i tried to load pages, it loads successfully just it doesn't loads my .css files giving MIME type not supported error. However, when i removes the "eventname"
app.get('/:event', (req, res) => {
res.render('event.hbs', {
name: req.user.displayName
});
})
Everything started wroking fine.
Why is this happening, am i doing something wrong in express?
I'm not 100% certain, but I'm pretty sure that this happens because the <link> tag you use to import the CSS file uses a relative path.
Let's imagine it looks like this ...
<link rel="stylesheet" type="text/css" href="styles.css">
... and the URL of the event page you're visiting is https://example.com/example-event. In that case the relative path used for the CSS will resolve to the absolute path https://example.com/styles.css which is – I assume – the correct path.
Now imagine that you're instead using the first code example and the URL is https://example.com/eventname/example-event. Now the URL of the CSS file is resolved to https://example.com/eventname/styles.css which is not the correct path.
The path, however, is still handled by the web server because it matches the URL wildcard you use for the event pages – /eventname/:event. That causes your application to render the event.hbs template which is obviously served with the MIME type text/html and not text/css as expected, hence the error MIME type not supported.
To fix this problem, you can:
use an absolute (relative to your application's domain) path (/styles.css – note the /)
use a valid relative path for every page (../styles.css in case of /eventname/:event)
Although both options work, I highly recommend the first one as it is easier to maintain.
If you get that error that mean your folder is not in the public directory. Move it to the public directory and change the route of your files to (/style.css)
Related
Why am I getting this error in console?
Refused to execute script from
'https://www.googleapis.com/customsearch/v1?key=API_KEY&q=flower&searchType=image&fileType=jpg&imgSize=small&alt=json'
because its MIME type ('application/json') is not executable, and
strict MIME type checking is enabled.
In my case it was a file not found, I typed the path to the javascript file incorrectly.
You have a <script> element that is trying to load some external JavaScript.
The URL you have given it points to a JSON file and not a JavaScript program.
The server is correctly reporting that it is JSON so the browser is aborting with that error message instead of trying to execute the JSON as JavaScript (which would throw an error).
Odds are that the underlying reason for this is that you are trying to make an Ajax request, have hit a cross origin error and have tried to fix it by telling jQuery that you are using JSONP. This only works if the URL provides JSONP (which is a different subset of JavaScript), which this one doesn't.
The same URL with the additional query string parameter callback=the_name_of_your_callback_function does return JavaScript though.
This result is the first that pops-up in google, and is more broad than what's happening here. The following will apply to an express server:
I was trying to access resources from a nested folder.
Inside index.html i had
<script src="./script.js"></script>
The static route was mounted at :
app.use(express.static(__dirname));
But the script.js is located in the nested folder as in: js/myStaticApp/script.js
I just changed the static route to:
app.use(express.static(path.join(__dirname, "js")));
Now it works :)
Try to use express.static() if you are using Node.js.
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do as below −
i.e. : app.use(express.static('public'));
This approach resolved my issue.
In my case, I was working on legacy code
and I have this line of code
<script type="text/javascript" src="js/i18n.js.php"></script>
I was confused about how this supposed to work this code was calling PHP file not js
despite it was working on the live server
but I have this error on the stage sever
and the content type was
content-type: text/html; charset=UTF-8
even it is text/javascript in the script tag
and after I added
header('Content-Type: text/javascript');
at the beginning for file i18n.js.php
the error is fixed
After searching for a while I realized that this error in my Windows 10 64 bits was related to JavaScript. In order to see this go to your browser DevTools and confirm that first. In my case it shows an error like "MIME type ('application/javascript') is not executable".
If that is the case I've found a solution. Here's the deal:
Borrowing user "ilango100" on https://github.com/jupyterlab/jupyterlab/issues/6098:
I had the exact same issue a while ago. I think this issue is specific to Windows. It is due to the wrong MIME type being set in Windows registry for javascript files. I solved the issue by editing the Windows registry with correct content type:
regedit -> HKEY_LOCAL_MACHINE\Software\Classes -> You will see lot of folders for each file extension -> Just scroll down to ".js" registry and select it -> On the right, if the "Content Type" value is other than application/javascript, then this is causing the problem. Right click on Content Type and change the value to application/javascript
enter image description here
Try again in the browser."
After that I've realized that the error changes. It doesn't even open automatically in the browser anymore. PGAdmin, however, will be open on the side bar (close to the calendar/clock). By trying to open in the browser directly ("New PGAdmin 4 window...") it doesn't work either.
FINAL SOLUTION: click on "Copy server URL" and paste it on your browser. It worked for me!
EDIT: Copying server URL might not be necessary, as explained by Eric Mutta in the comment below.
I accidentally named the js file .min instead of .min.js ...
Python flask
On Windows, it uses data from the registry, so if the "Content Type" value in HKCR/.js is not set to the proper MIME type it can cause your problem.
Open regedit and go to the HKEY_CLASSES_ROOT make sure the key .js/Content Type has the value text/javascript
C:\>reg query HKCR\.js /v "Content Type"
HKEY_CLASSES_ROOT\.js
Content Type REG_SZ text/javascript
In my case (React app), just force cleaning the cache and it worked.
I had my web server returning:
Content-Type: application\javascript
and couldn't for the life of me figure out what was wrong. Then I realized I had the slash in the wrong direction. It should be:
Content-Type: application/javascript
In my case, while executing my typescript file,
I wrote:
<script src="./script.ts"></script>
Instead of:
<script src="./script.js"></script>
In my case Spring Security was looking for authentication before allowing calls to external libraries. I had a folder /dist/.. that I had added to the project, once I added the folder to the ignore list in my WebSecurityConfig class, it worked fine.
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**", "/error", "/dist/**");
Check for empty src in script tag.
In my case, i was dynamically populating src from script(php in my case), but in a particular case src remained empty, which caused this error. Out was something like this:
<script src=""></script> //empty src causes error
So instead of empty src in script tag, I removed the script tag all together.
Something like this:
if($src !== ''){
echo '<script src="'.$src.'"></script>';
}
You can use just Use type
or which you are using you choose that file type
My problem was that I have been putting the CSS files in the scripts definition area just above the end of the
Try to check the files spots within your pages
I am using SpringMVC+tomcat+React
#Anfuca's answer does not work for me(force cleaning the browser's cache)
I used Filter to forward specific url pattern to the React's index.html
public class FrontFilter extends HttpFilter {
#Override
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
boolean startsWithApi = requestURI.startsWith("/api/");
boolean isFrontendUri = requestURI.startsWith("/index.html");
if (!startsWithApi && !isFrontendUri) {
req.getRequestDispatcher("/index.html").forward(req, res);
}
super.doFilter(wrapped, res, chain);
}
}
There is no Spring Security problem bcs my filter executes before Spring Security's
but I still see the same error and find here
Then I realized that I forgot adding one more condition for JS and CSS:
boolean startsWithStatic = requestURI.startsWith(contextPath + "/static");
Add this to my if condition and problem solved, no more error with MIME type or ('text/html') with js and css
Root cause is that I incorrectly forward JS and CSS type to HTML type
I got the same error. I realized my app.js was in another folder. I just moved it into that folder where my index.html file is and it resolved.
In Angular Development try this
Add the code snippet as shown below to the entry html. i.e "index.html" in reactjs
<div id="wrapper"></div>
<base href="/" />
If you have a route on express such as:
app.get("*", (req, res) => {
...
});
Try to change it for something more specific:
app.get("/", (req, res) => {
...
});
For example.
Or else you just might find yourself recursively serving the same HTML template over and over...
In my case I had a symlink for the 404'd file and my Tomcat was not configured to allow symlinks.
I know that it is not likely to be the cause for most people, but if you are desperate, check this possibility just in case.
I hade same problem then i fixed like this
change "text/javascript"
to
type="application/json"
I solved my problem by adding just ${pageContext.request.contextPath} to my jsp path .
in stead of :
<script src="static/js/jquery-3.2.1.min.js"></script>
I set :
<script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script>
I am writing a website using NodeJS and Express. After specifying a link with 2 route parameters:
app.get('/game/:port/:player/', function(req, res) {
res.sendFile(path.join(__dirname, '/game/game.html'));
})
-the result is a blank white page.
Looking at DevTools, I saw the error Uncaught SyntaxError: Unexpected token '<' game.js:1. It looks like the browser is interpreting the html file as a JavaScript file! I think this is because the browser tries to fetch the js and css files from /game/(portnumber)/(playernumber) instead of from /game. And the css shows up as the actual HTML file:
However, another route that I have with only 1 route parameter works just fine! I am still relatively new to Express so I don't really understand how fetching directories works.
Is there any way to fix this directory error without manually specifying every single path in which there are HTML files?
This doesn't really have anything to do with Express. It is basic URL resolution.
The browser will request /game/3561/2 and get an HTML document back
That document will tell it to load ./game.js which it will resolve to
/game/3561/game.js (since a URL starting with a . means "resolve the path from current directory").
That isn't the URL of your JS file, so you get an HTML document instead — where :player is game.js.
You need to write the actual URL to your JS file in the src attribute.
You can use the express.static middleware to specify a public directory your clients have access to:
https://expressjs.com/en/starter/static-files.html
app.use('/static', express.static('public'))
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
I have a simple nodejs application with folder structure like this (not a full structure, but enough for this question).
index.js
views
- index.ejs
- about.ejs
In index.js, I have
app.use("/", (request, response) => {
response.render('index')
})
app.use("/about", (request, response) => {
response.render('about')
})
// Also tried with extension (index.ejs and about.ejs)
In index.ejs, I have
About
The problem
When I go to root url (localhost:port/), index.ejs is displayed.
In index.ejs, I click on the link About, the url is changed to (localhost:port/about), but about.ejs is not rendered. However, checking F12 sources in browser (Microsoft Edge Chrominum), about.ejs is in there.
When I go to the link directly by typing the url to url bar, index.js is displayed. The behavior (in F12/sources) is the same compared step 2.
When I comment out (app.use("/") block in index.js, about.ejs is accessible and displayed on screen.
Note, the navigation works perfectly if they are html pages and served by node.js server. Everything has been test only on local server.
Question
What is the cause of this and how to fix?
Why do I use EJS?
I want to create a dynamic front end based on DB query.
There seems to be multiple questions about this on Stackoverflow, I have tried multiple of them and none fix my issue, or clearly explain the cause.
As #Quentin answered, the issue is due to my use of use. For the request, which is GET in this case, I have to use get function, and it fixes the problem.
use is applicable when I want to decompose my index.js or use middleware.
FILES
https://github.com/microcyberz/expensify
When I access this URL http://localhost:8081/edit/01 with built-in navigation of react-router, it works fine. Route is <Route path="/edit/:id/" component={EditExpensePage} />.
But when I put the same URL directly in the browser, I get following two lines of error in console and page doesn't render anything.
Errors
GET http://localhost:8081/edit/bundle.js net::ERR_ABORTED
GET http://localhost:8081/edit/bundle.js 404 (Not Found)
I will be thankful for the help.
Here's your problem:
https://github.com/microcyberz/expensify/blob/master/public/index.html#L13
You're loading the bundle.js relative to the current path, in stead of absolute from the root. Change this to /bundle.js and you're good to go.
In your example, the js is loaded relative to the current url, resolving from /edit/123 to /edit/bundle.js
This is happening because your server is not redirecting to the index file. I mean what's behind http://localhost:8081? Is it node? Are you sure that every single request is handled the same way?
Also you may check how you include your bundle.js. Is the path relative like ./assets/js/bundle.js or absolute like /assets/js/bundle.js? Should be absolute.
This problem will also appear when using webpack and the HtmlWebpackPlugin. It can be solved by using the publicPath config option, which will prepend each script tag with a /:
//webpack.config.js
{
...
plugins: [
new HtmlWepbackPlugin({
...
publicPath: '/'
})
]
}
Why am I getting this error in console?
Refused to execute script from
'https://www.googleapis.com/customsearch/v1?key=API_KEY&q=flower&searchType=image&fileType=jpg&imgSize=small&alt=json'
because its MIME type ('application/json') is not executable, and
strict MIME type checking is enabled.
In my case it was a file not found, I typed the path to the javascript file incorrectly.
You have a <script> element that is trying to load some external JavaScript.
The URL you have given it points to a JSON file and not a JavaScript program.
The server is correctly reporting that it is JSON so the browser is aborting with that error message instead of trying to execute the JSON as JavaScript (which would throw an error).
Odds are that the underlying reason for this is that you are trying to make an Ajax request, have hit a cross origin error and have tried to fix it by telling jQuery that you are using JSONP. This only works if the URL provides JSONP (which is a different subset of JavaScript), which this one doesn't.
The same URL with the additional query string parameter callback=the_name_of_your_callback_function does return JavaScript though.
This result is the first that pops-up in google, and is more broad than what's happening here. The following will apply to an express server:
I was trying to access resources from a nested folder.
Inside index.html i had
<script src="./script.js"></script>
The static route was mounted at :
app.use(express.static(__dirname));
But the script.js is located in the nested folder as in: js/myStaticApp/script.js
I just changed the static route to:
app.use(express.static(path.join(__dirname, "js")));
Now it works :)
Try to use express.static() if you are using Node.js.
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do as below −
i.e. : app.use(express.static('public'));
This approach resolved my issue.
In my case, I was working on legacy code
and I have this line of code
<script type="text/javascript" src="js/i18n.js.php"></script>
I was confused about how this supposed to work this code was calling PHP file not js
despite it was working on the live server
but I have this error on the stage sever
and the content type was
content-type: text/html; charset=UTF-8
even it is text/javascript in the script tag
and after I added
header('Content-Type: text/javascript');
at the beginning for file i18n.js.php
the error is fixed
After searching for a while I realized that this error in my Windows 10 64 bits was related to JavaScript. In order to see this go to your browser DevTools and confirm that first. In my case it shows an error like "MIME type ('application/javascript') is not executable".
If that is the case I've found a solution. Here's the deal:
Borrowing user "ilango100" on https://github.com/jupyterlab/jupyterlab/issues/6098:
I had the exact same issue a while ago. I think this issue is specific to Windows. It is due to the wrong MIME type being set in Windows registry for javascript files. I solved the issue by editing the Windows registry with correct content type:
regedit -> HKEY_LOCAL_MACHINE\Software\Classes -> You will see lot of folders for each file extension -> Just scroll down to ".js" registry and select it -> On the right, if the "Content Type" value is other than application/javascript, then this is causing the problem. Right click on Content Type and change the value to application/javascript
enter image description here
Try again in the browser."
After that I've realized that the error changes. It doesn't even open automatically in the browser anymore. PGAdmin, however, will be open on the side bar (close to the calendar/clock). By trying to open in the browser directly ("New PGAdmin 4 window...") it doesn't work either.
FINAL SOLUTION: click on "Copy server URL" and paste it on your browser. It worked for me!
EDIT: Copying server URL might not be necessary, as explained by Eric Mutta in the comment below.
I accidentally named the js file .min instead of .min.js ...
Python flask
On Windows, it uses data from the registry, so if the "Content Type" value in HKCR/.js is not set to the proper MIME type it can cause your problem.
Open regedit and go to the HKEY_CLASSES_ROOT make sure the key .js/Content Type has the value text/javascript
C:\>reg query HKCR\.js /v "Content Type"
HKEY_CLASSES_ROOT\.js
Content Type REG_SZ text/javascript
In my case (React app), just force cleaning the cache and it worked.
I had my web server returning:
Content-Type: application\javascript
and couldn't for the life of me figure out what was wrong. Then I realized I had the slash in the wrong direction. It should be:
Content-Type: application/javascript
In my case, while executing my typescript file,
I wrote:
<script src="./script.ts"></script>
Instead of:
<script src="./script.js"></script>
In my case Spring Security was looking for authentication before allowing calls to external libraries. I had a folder /dist/.. that I had added to the project, once I added the folder to the ignore list in my WebSecurityConfig class, it worked fine.
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**", "/error", "/dist/**");
Check for empty src in script tag.
In my case, i was dynamically populating src from script(php in my case), but in a particular case src remained empty, which caused this error. Out was something like this:
<script src=""></script> //empty src causes error
So instead of empty src in script tag, I removed the script tag all together.
Something like this:
if($src !== ''){
echo '<script src="'.$src.'"></script>';
}
You can use just Use type
or which you are using you choose that file type
My problem was that I have been putting the CSS files in the scripts definition area just above the end of the
Try to check the files spots within your pages
I am using SpringMVC+tomcat+React
#Anfuca's answer does not work for me(force cleaning the browser's cache)
I used Filter to forward specific url pattern to the React's index.html
public class FrontFilter extends HttpFilter {
#Override
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
boolean startsWithApi = requestURI.startsWith("/api/");
boolean isFrontendUri = requestURI.startsWith("/index.html");
if (!startsWithApi && !isFrontendUri) {
req.getRequestDispatcher("/index.html").forward(req, res);
}
super.doFilter(wrapped, res, chain);
}
}
There is no Spring Security problem bcs my filter executes before Spring Security's
but I still see the same error and find here
Then I realized that I forgot adding one more condition for JS and CSS:
boolean startsWithStatic = requestURI.startsWith(contextPath + "/static");
Add this to my if condition and problem solved, no more error with MIME type or ('text/html') with js and css
Root cause is that I incorrectly forward JS and CSS type to HTML type
I got the same error. I realized my app.js was in another folder. I just moved it into that folder where my index.html file is and it resolved.
In Angular Development try this
Add the code snippet as shown below to the entry html. i.e "index.html" in reactjs
<div id="wrapper"></div>
<base href="/" />
If you have a route on express such as:
app.get("*", (req, res) => {
...
});
Try to change it for something more specific:
app.get("/", (req, res) => {
...
});
For example.
Or else you just might find yourself recursively serving the same HTML template over and over...
In my case I had a symlink for the 404'd file and my Tomcat was not configured to allow symlinks.
I know that it is not likely to be the cause for most people, but if you are desperate, check this possibility just in case.
I hade same problem then i fixed like this
change "text/javascript"
to
type="application/json"
I solved my problem by adding just ${pageContext.request.contextPath} to my jsp path .
in stead of :
<script src="static/js/jquery-3.2.1.min.js"></script>
I set :
<script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script>