Dynamic route page failing to script on production [duplicate] - javascript

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>

Related

Uncaught SyntaxError: Unexpected token < on each js file that invoked in the index html

I am using mean stack to build a website, when testing, chrome returns the error like:
Uncaught SyntaxError: Unexpected token < angular.js:1.
I don't know what's wrong and what should i do.
Here is the directory of my app:
E-study
-client
-app
-components
-all the libraries are here.
-index.html
-controllers.js
-node_modules
-server
-config
-server.js
And I run the server in E-study like :node server/config/server.js
The scripts in the index.html is<script src="client/components/angular/angular.js"></script>
Just don't know why all the js files are changed to index.html when open in the browser.
open up those library files and see if there are some extra symbol < probably you will find it in the beginning.. if still not able to fix... simply download the fresh library (if those are libraries) from the internet and try again.
make sure that you don't put <script> </script> tags in the included .js files. that is an incorrect syntax for script files.
also make sure you are providing the correct path??? providing incorrect path can return a builtin customized error page. which is html. may be that is the source of error because returned page is HTML which is most likely going to start with a < symbol. and offcourse not a js file.
to ensure that the incorrect path is the issue just copy the path you included in the code and and paste into your favorite browsers url bar and hit enter. if you are not getting the script in plain text.. then it means you are not providing the correct path.
and if it is return a customized error page like .. 404 not found then probably it is returning the html and this is where the error is coming from.
In external js files, which you refer in some other files, don't use <script>..</script> tag.
For express server try to set the static path to entire project folder.It worked for me
app.use(express.static(__dirname ));
Could be a ReCaptcha bot checker type thing intercepting requests for JS files and serving up an HTML page instead, which is invalid HTML so it throws the < is invalid message error.
I know siteground specifically has issues with this intercepting CDN routed traffic.
Check with the host to remove this issue, in this case it's their anti-bot security setup. This has remedied these issues with Siteground for me.

Refused to execute script, strict MIME type checking is enabled?

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>

cannot find js file

I have stucture code like this:
I try to load javascript into php file like this:
But i have an error like this:
This is my html :
And this is another javascript:
And i try to copy paste the link, and i got an error 404 not found. How can i fix it? Thanks.
Permissions
When the host is correct, and the file is in the right place, and you have no other networking problems, you may sometimes still get a 404 because of bad file permissions. If a server does not have permission to access a file, it may send out a 404 error in response. The reason why some "Not Authorized" error is not given instead, is that this would reveal more information about the files than you, the owner of the server, may intend. The way to respond to requests for privileged files without revealing whether or not they exist is to give a 404.
On Windows, you can view and change the permissions from the File Explorer by right-clicking on the file or folder, then going to Properties -> Security -> Edit. For more information, see the notes on permissions on Microsoft's site.
File Types
Besides permissions, a server must also be configured to serve the type of file you are accessing. If files with different extensions are served, but .js files are not, check the configuration of your server to make sure that .js files aren't blacklisted (or not whitelisted, as the case may be).
Directory Location
You should also verify that the files are actually stored in the top-most directory of the web server if that's how you are accessing them. If they aren't, you may need to prefix the path with the path from the webserver root to your application directory. E.g., instead of fusioncharts/..., you may need /path/to/fusioncharts/... or ../../path/to/fusioncharts.
Other Considerations
In your particular case, you should also verify that the files inside the fusioncharts folder are actually structured the way you think. (E.g., is there really a js/[insert name here].js file inside the fusioncharts folder?
If none of that solves your problem, try to take something that is working and gradually make it more and more similar to the files that aren't working. By figuring out at which point you go from a working setup to a not working setup, you may discover the problem.
If you are referring to a file with path: /ui/new-file.js
then,
1.In html file include
<script type="text/javascript" src="/ui/new-file.js"></script>
2.In server.js or app.js whichever you have, include
app.get('/ui/new-file.js', function (req, res) {
res.sendFile(path.join(__dirname, 'ui', 'login-file.js'));
});
Assuming you are using codeigniter, you can use base_url() function to include JS files in your codeignitor view template file.
<script src="<?php echo base_url(); ?>fusioncharts/js/fusioncharts.js" type="text/javascript"></script>
codeigniter default view template is called welcome_message.php and this file is located in application/view folder.
This is how I include js files in my codeigniter projects. Hope this will help.
In the html you can write *script** in the head or in the body, but not in your file js, delete this in fusionCharts.js
<script type=text/javascript>
In fusionCharts.js write only the function without the script
If you are developing locally, try clearing your cache.
Google Chrome likes to use the cached JavaScript files instead of the real ones.
Clearing your cache should resolve the issue.

How to set content type of JavaScript files in Django

I have a Django application, which requires several JavaScript files.
In Chrome I get the error "Resource interpreted as Script, but transferred with MIME type text/html".
AFAIK (see 2) in order to fix this problem, I need to configure Django so that JavaScript files are returned with content-type "application/x-javascript".
How can I do this in Django?
UPDATE: I followed the advice by Daniel Roseman and found following solution.
1) Modify urls.py:
urlpatterns = patterns('',
...
url(r'.*\.js$', java_script),
...
)
2) Add following function to views.py:
def java_script(request):
filename = request.path.strip("/")
data = open(filename, "rb").read()
return HttpResponse(data, mimetype="application/x-javascript")
I had an issue with Django serving javascript files as text/plain with the included server, which doesn't work too well with ES6 modules. I found out here that you could change file extension associations by placing the following lines in your settings.py:
#settings.py
if DEBUG:
import mimetypes
mimetypes.add_type("application/javascript", ".js", True)
and javascript files were now served as application/javascript.
I suspect the problem is not what you think it is. What is probably actually happening is that your JS files are not being served at all: instead, the Django error page is being sent. You need to figure out why.
Expanding on Alexandre's answer using put the below code into settings.py of your main project. After that you will need to clear your browser cache (you can test it by opening an incognito window as well) in order to get the debug panel to appear.
if DEBUG:
import mimetypes
mimetypes.add_type("application/javascript", ".js", True)
Since this doesn't prevent scripts from being interpreted correctly by the browser, why is this a problem? runserver is only for development (not production use), and as such is not a full blown web server.
You should continue to use it in development and when you move to production configure your webserver appropriately for static files.
However, if you absolutely must use the development server to serve static files; see how to serve static files.
For Django use request context in views :
return render_to_response('success.html', {'object': varobject},context_instance=RequestContext(request))
I ran into that error today even after adding #piephai s solution to my settings.py. I then noticed that #Daniel Roseman got it right as well:
My import paths were wrong, I had to add ".js" to all of them, for example:
import {HttpTool} from "./requests"; became import {HttpTool} from "./requests.js";
Makes sense after thinking about how routes for static files are generated.
The solution to the problem is describe in the documentation
For Windows, you need to edit the registry. Set HKEY_CLASSES_ROOT\.js\Content Type to text/javascript.

Including .inc javascript file in ASP doesn't work, only .js does

New to ASP and probably never named a Javascript file ".inc" :-)
But that seems to be the norm where I'm currently working.
I observed that right on the first page I started getting these javascript errors
Message: 'globalVariableXXX' is undefined
I found that the javascript file wasn't getting called at all.
Just changed the name to ".js" and it worked !!
The ASP file includes the JavaScript file like this :
<SCRIPT LANGUAGE="Javascript" SRC="include/MenuCode.inc"></SCRIPT>
But there are 100's of these ".inc" files and 100's of references to them, hence don't want to go with this solution.
I'd rather understand it..
Any idea why it would've worked in the first place and why it isn't now ?
I'm sure I'm missing something pretty basic in ASP..
Another point : This application is installed on another server and it works just fine there when I hit it. I'm trying to install it on this new box.
Where I made the change for it to work:
In IIS, Right click on the name of the machine and the Mime Types are right over there. Checked the old server and it had the settings for ".inc", copied them and it started working :) Thanks all.
Maybe someone changed the webserver to prevent it serving .inc files ?
In the management console (inetmgr) right click the website and choose Properties. Go to "home directory" tab and click Configuration.
You will probably see the .inc extension there (in the mapping tab) meaning those files are parsed by the ASP engine.
Remove the item from the mappings table, apply and you should be able to parse those files as raw data.
The proper way to use a script tag for javascript is with the type attribute, such as
<script type="text/javascript" src="include/MenuCode.inc"></script>
see: http://www.w3schools.com/tags/tag_script.asp
language isn't even listed as a supported attribute by the standard..
Edit: The reason .js worked and .inc didn't is .js is in the mime type definitions of the server as a JAVASCRIPT mime type by default. If not using an extension configured as text/javascript by default, you have to tell the browser what to treat the file as somehow. This is why the text attribute of script is a required attribute as per html 4.01.

Categories

Resources