Browser thinks that the HTML file is a js file - javascript

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

Related

Getting MIME type not supported

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)

How can I make a POST request to a php file within the same angular application?

I have a strange situation where I need to send some image data to a php file from within the angular application itself... yes, the php file resides in the angular docroot.
Every time I try to upload image data (from the browser) to this file, the application doesn't seem to go through to it. Instead, I get back a response that is the entire index.html code. I understand that this is probably because I am using ui.router to handle my routing, and have it defaulting to index.html. However, I have tried to add app.use("/upload.php", express.static(path.join(__dirname, '/upload.php'))); to my node server script... in hope that the /upload.php url would be succesfully routed... however, I still only get back index.html code and it seems that the upload.php file is never reached.
Can anybody provide any hinters? Much appreciated.

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.

External javascript in html is sent incorrectly to the server

I'm running a Node.js server along with an Angular frontend. One of the Angular dependencies I'm using requires me to import a javascript file into my html page, by the name of swing.js. However, when I try to do this, it sends the required file as an http request to the server, resulting in requests that look like the following:
http://localhost:3000/home/me/app/node_modules/angular-swing/dist/swing.js
Obviously, this comes up as a 404. As an alternative, I've tried changing
<script src="/home/me/app/node_modules/angular-swing/dist/swing.js"></script>
into
<script src="swing.js"></script>
and then on the server-side, doing:
app.get('swing.js', function(req, res){
res.sendFile('home/me/app/node_modules/angular-swing/dist/swing.js');
});
This works a little more, but then the file doesn't run properly, as I'm assuming it's no longer in the npm environment it needs to be in. I've tried multiple iterations of changing
<script src="/home/me/app/node_modules/angular-swing/dist/swing.js"></script>
into something that uses periods (.) to represent more relative paths, but that doesn't appear to work either. Overall, I'm very stuck, and would appreciate any insight. If it's of any use, I'm also using:
app.use(express.static(__dirname+'/public'));
Making my comments into an answer...
node.js does not serve any files by default so any script files that you need sent from your server to the client upon request need an explicit route to handle them or they need some generic route that knows how to handle all the requested script files.
swing.js in the client is not part of any "NPM environment". It's running the browser at that point, not in any NPM enviornment. It's possible that swing.js itself needs some other scripts or resources that also need routes and that's why it doesn't work after you make an explicit route for it. You can probably examine the specific errors in the console to give you a clue why it isn't working.
You may also want to read this: How to include scripts located inside the node_modules folder?

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.

Categories

Resources