Cannot load the CSS with NodeJS - html

I am beginner to NodeJS and facing problem in loading the CSS. Here is my code.
I am just creating a server running in 9090 port and loading the default HTML file.
var server = http.createServer(function(request, response) {
var html = fs.readFileSync('./FirstApp/HtmlPages/index.html');
response.writeHead(200,{"Content-Type": "text/html"});
response.write(html);
response.end();
});
server.listen(9090);
On Loading http://localhost:9090/ i am able to see the index.html html page but not able to see the linked css feature.(If i just load my index.html in browser i am able to see css feature but not through the server)
This is my simple HTML.
<html>
<head>
<link type="text/css" rel="stylesheet" href="./css/styles.css">
</head>
<body>
<h2 class="heading"><em>Login Page</em></h2>
</body>
</html>
CSS file
.heading {
text-align: center;
}
I can see below warning in browser console
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:9090/css/styles.css".
any help would be much appreciated

The problem is that you have a created a web server that only serves a single file, the index.html. It does not read any CSS file from the local file system, and it does not serve any CSS files.
You could analyze the incoming request and see if the path of the request‘s URL points to the CSS file. If it does, read the CSS file instead of the HTML file and return it with the response.
Here's a working, modified version of your code (assuming that styles.css is located in a subdirectory of the dir where your index.html is located):
var server = http.createServer(function(request, response) {
if (request.url.match(/^\/css\//)) {
var css = fs.readFileSync('./FirstApp/HtmlPages' + request.url);
response.writeHead(200,{"Content-Type": "text/css"});
response.write(css);
response.end();
return;
}
var html = fs.readFileSync('./FirstApp/HtmlPages/index.html');
response.writeHead(200,{"Content-Type": "text/html"});
response.write(html);
response.end();
});
server.listen(9090);
Please note: I would only do this for learning purposes, not for building an actual production web application. For that, I would use an existing HTTP server solution, for example Express.

I would suggest checking your file path is correct when linking to the css file. Try removing the . and have your path as /css/styles.css (but it comes down to ensuring that you have the correct path.
As a beginner, a common mistake might be that you forgot to save your css file after you made your edits.
Also, you should use the chrome developer tool (right click on page and inspect) to see if your css is already being applied to your html.
If you can show us the index.html code, that might help as well.

Related

Is there a way to fetch files inside a matlab uihtml component?

I am using a uihtml component inside a uifigure that loads a HTML file in its HTMLSource property. The HTML file just tries to fetch the contents of a text file located in the same folder, and outputs them inside a div component. The body in the HTML looks something like this:
<body>
<div id="viewer"></div>
<script>
fetch("./example.txt")
.then(response => response.text)
.then(textString => {
document.getElementById('viewer').innerHTML = textString;
});
</script>
</body>
The problem is that I always get a "Page Not Found" (the status from the fetch response is 404). The documentation of uihtml says: Common web file types, like JavaScript and CSS, can be referenced from the HTML file you specify for the HTMLSource property, but other web file types might not be supported., so I am not sure if it is even possible to fetch a text/pdf/any other file.
From what I understand, when calling uihtml MATLAB injects an iframe on the webpage displayed by the uifigure. This iframe runs on a local web server, and whenever you append a script tag with a source, the script is also accessed from the web server. For example,
<body>
<div id="viewer"></div>
<script id="script-id" src = "./example.js"></script>
<script>
document.getElementById("viewer").innerHTML = document.getElementById("script-id").src;
</script>
</body>
would display the source of the js file, which corresponds to something like:
https://localhost:31515/static/xxxxxxxx/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/example.js
That same location of the file we could get by appending the undocumented
connector.getBaseUrl
matlab.ui.internal.URLUtils.parseURL('/example.js',0)
I have tried fetching the text file with the full path to that web server location
(https://localhost:31515/static/.../example.txt)
but the 404 error persists.
At this level of HTML/JS is where I start to struggle. It looks like there should be some way to fetch the data of the file since scripts can be loaded, but I can't find a way. Does anybody know how to successfully fetch the file? Do we need a special credential in the fetch request or something like that?

Location of webroot (for css file) in Perfect app

I've cloned the PerfectTemplate project and am using it to serve up html as follows…
import PerfectHTTP
import PerfectHTTPServer
var routes = Routes()
routes.add(method: .get, uri: "/test") { request, response in
response.addHeader(.contentType, value: "text/html")
response.setBody(string: """
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="Welcome">Hello</div>
</body>
</html>
""")
response.completed()
}
routes.add(method: .get,
uri: "/**",
handler: StaticFileHandler(documentRoot: "./webroot", allowResponseFilters: true).handleRequest)
try HTTPServer.launch(name: "localhost",
port: 8181,
routes: routes,
responseFilters: [(PerfectHTTPServer.HTTPFilter.contentCompression(data: [:]), HTTPFilterPriority.high)])
I'm compiling and running with Xcode, and http://localhost:8181/test is returning the html as expected.
The problem is the location of the external css file. As far as I can tell this should be in a folder called webroot, but where should that folder be when running locally?
For reference, I'm coming at this as an iOS dev, so my knowledge of web development and server config is limited.
Update
Per a suggestion on the Perfect Slack group, I added the css file to the project folder (the same folder as Package.swift), and set the Working Directory of the scheme $(PROJECT_DIR) - but I’m getting a 404 trying to load http://localhost:8181/style.css
With help from the Perfect Slack group, I found a solution. The missing piece for me was the webroot folder. I'd assumed this was some kind of alias, but it turns out that you do need to create an actual folder called webroot. So…
Set the Working Directory of the scheme to $(PROJECT_DIR)
In the project folder, create a folder named webroot and add the css file to that folder. It should look like this…
I'm sure all the seasoned web devs are laughing at me right now!

How to include a code fragment from a text file into html?

Is there a simple way (or what could be the simplest way) to include a html-code fragment, which is stored in a text file, into a page code?
E.g. the text file fragment.txt contains this:
<b><i>External text</i></b>
And the page code should include this fragment "on the fly". (Without php ...?)
The Javascript approach seems to be the preferred one. But with the examples below you possibly can get problems with cross origin requests (localhost to internet and vice versa) or you can have security problems when including external scripts which are not served via HTTPS.
An inline solution without any external libraries would be:
<!DOCTYPE html>
<html>
<body>
<div id="textcontent"></div>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById('textcontent').innerText = xhttp.responseText;
};
xhttp.open("GET", "content.txt", true);
xhttp.send();
</script>
</body>
</html>
Here you need a file content.txt in the same folder as the HTML file. The text file is loaded via AJAX and then put into the div with the id textcontent. Error handlings are not included in the example above. Details about XMLHttpRequest you can find at http://www.w3schools.com/xml/xml_http.asp.
EDIT:
As VKK mentioned in another answer, you need to put the files on a server to test it, otherwise you get Cross-Origin-Errors like XMLHttpRequest cannot load file:///D:/content.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
You need to use Javascript to do this (or perhaps an iframe which I would avoid). I'd recommend using the JQuery framework. It provides a very simply DOM method (load) that allows you to load the contents of another file into an HTML element. This is really intended for AJAX calls, but it would work in your use case as well. The fragment.txt would need to be in the same server directory as the html page (if it's in a different directory just add on a path).
The load method is wrapped in the $(document).ready event handler since you can only access/edit the contents element after the DOM (a representation of the page) has been loaded.
Most browsers don't support local AJAX calls (the load method uses AJAX) - typically the HTML and txt files would be uploaded to a server and then the html file would be accesed on the client. Firefox does support local AJAX though, so if you want to test it locally use Firefox.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script>
$(document).ready(function() {
$("#contents").load("fragment.txt");
});
</script>
</head>
<body>
<div id="contents"></div>
</body>
</html>
With javascript. I use it.
Example:
<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
<body>
<div w3-include-html="content.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
</html>

I want to render static html in Express.js, but still have app.get() methods for logic

This seems like a ridiculous thing to be hung up on, but I would like to display html files from within app.get() methods. It seems like every answer I've come across uses the solution app.use(express.static(__dirname + '/public'));, but then that does not allow for logic from the server.
What I would like to do, is have my .html files be rendered by express, so I can keep some basic logic:
app.get('/', function(res, req) {
if (condition) {
res.render('this.html');
}
else {
res.render('that.html');
}
}
It seems so silly to me that this is only meant for template files, and that I must not be seeing something simple to make this work.
Edit: Using sendFile does not seem to allow the HTML to include external files, javascript / css.
You can use res.sendfile() (res.sendFile() for new version) to render html files.
Update for question in comment:
You can include your css and javascript files in the html file (you might need to specify the paths for your resources correct to get them loaded):
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="myscripts.js"></script>
</head>

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

I have this problem. Chrome continues to return this error
Resource interpreted as stylesheet but transferred with MIME type text/html
The files affected by this error are just the Style, chosen and jquery-gentleselect (other CSS files that are imported in the index in the same way work well and without error). I've already checked my MIME type and text/css is already on CSS.
Honestly I'd like to start by understanding the problem (a thing that seems I cannot do alone).
i'd like to start by understanding the problem
Browsers make HTTP requests to servers. The server then makes an HTTP response.
Both requests and responses consist of a bunch of headers and a (sometimes optional) body with some content in it.
If there is a body, then one of the headers is the Content-Type which describes what the body is (is it an HTML document? An image? The contents of a form submission? etc).
When you ask for your stylesheet, your server is telling the browser that it is an HTML document (Content-Type: text/html) instead of a stylesheet (Content-Type: text/css).
I've already checked my myme.type and text/css is already on css.
Then something else about your server is making that stylesheet come with the wrong content type.
Use the Net tab of your browser's developer tools to examine the request and the response.
Using Angular?
This is a very important caveat to remember.
The base tag needs to not only be in the head but in the right location.
I had my base tag in the wrong place in the head, it should come before any tags with url requests. Basically placing it as the second tag underneath the title solved it for me.
<base href="/">
I wrote a little post on it here
I also had problem with this error, and came upon a solution. This does not explain why the error occurred, but it seems to fix it in some cases.
Include a forward slash / before the path to the css file, like so:
<link rel="stylesheet" href="/css/bootstrap.min.css">
My issue was simpler than all the answers in this post.
I had to setup IIS to include static content.
Setting the Anonymous Authentication Credentials to Application Pool Identity did the trick for me.
Try this <link rel="stylesheet" type="text/css" href="../##/yourcss.css">
where ## is your folder wherein is your .CSS - file
Don't forget about the: .. (double dots).
I was also facing the same problem. And after doing some R&D, I found that the problem was with the file name. The name of the actual file was "lightgallery.css" but while linking I has typed "lightGallery.css".
More Info:
It worked well on my localhost (OS: Windows 8.1 & Server: Apache).
But when I uploaded my application to a remote server ( Different OS & Web server than than my localhost) it didn't work, giving me the same error as yours.
So, the issue was the case sensitivity (with respect to file names) of the server.
In case you serve static css with nginx you should add
location ~ \.css {
add_header Content-Type text/css;
}
location ~ \.js {
add_header Content-Type application/x-javascript;
}
or
location ~ \.css{
default_type text/css;
}
location ~ \.js{
default_type application/x-javascript;
}
to nginx conf
Based on the other answers it seems like this message has a lot of causes, I thought I'd just share my individual solution in case anyone has my exact problem in the future.
Our site loads the CSS files from an AWS Cloudfront distribution, which uses an S3 bucket as the origin. This particular S3 bucket was kept synced to a Linux server running Jenkins. The sync command via s3cmd sets the Content-Type for the S3 object automatically based on what the OS says (presumably based on the file extension). For some reason, in our server, all the types were being set correctly except .css files, which it gave the type text/plain. In S3, when you check the metadata in the properties of a file, you can set the type to whatever you want. Setting it to text/css allowed our site to correctly interpret the files as CSS and load correctly.
#Rob Sedgwick's answer gave me a pointer, However, in my case my app was a Spring Boot Application. So I just added exclusions in my Security Config for the paths to the concerned files...
NOTE - This solution is SpringBoot-based... What you may need to do might differ based on what programming language you are using and/or what framework you are utilizing
However the point to note is;
Essentially the problem can be caused when every request, including
those for static content are being authenticated.
So let's say some paths to my static content which were causing the errors are as follows;
A path called "plugins"
http://localhost:8080/plugins/styles/css/file-1.css
http://localhost:8080/plugins/styles/css/file-2.css
http://localhost:8080/plugins/js/script-file.js
And a path called "pages"
http://localhost:8080/pages/styles/css/style-1.css
http://localhost:8080/pages/styles/css/style-2.css
http://localhost:8080/pages/js/scripts.js
Then I just add the exclusions as follows in my Spring Boot Security Config;
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(<comma separated list of other permitted paths>, "/plugins/**", "/pages/**").permitAll()
// other antMatchers can follow here
}
}
Excluding these paths "/plugins/**" and "/pages/**" from authentication made the errors go away.
Cheers!
Using Angular
In my case using ng-href instead of href solved it for me.
Note :
I am working with laravel as back-end
If you are on JSP, this problem can come from your servlet mapping.
if your mapping takes url by defaut like this:
#WebServlet("/")
then the container interpret your css url, and goes to the servlet instead of going to the css file.
i had the same issue, i changed my mapping and now everyting works
i was facing the same thing, with sort of the same .htaccess file for making pretty urls. after some hours of looking around and experimenting. i found out that the error was because of relatively linking files.
the browser will start fetching the same source html file for all the css, js and image files, when i would browse a few steps deep into the server.
to counter this you can either use the <base> tag on your html source,
<base href="http://localhost/assets/">
and link to files like,
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/script.js"></script>
or use absolute links for all your files.
<link rel="stylesheet" type="text/css" href="http://localhost/assets/css/style.css" />
<script src="http://localhost/assets/js/script.js"></script>
<img src="http://localhost/assets/images/logo.png" />
I have a similar problem in MVC4 using forms authentication. The problem was this line in the web.config,
<modules runAllManagedModulesForAllRequests="true">
This means that every request, including those for static content, being authenticated.
Change this line to:
<modules runAllManagedModulesForAllRequests="false">
I also face this problem recently on chrome. I just give absolute path to my CSS file problem solve.
<link rel="stylesheet" href="<?=SS_URL?>arica/style.css" type="text/css" />
For anyone that might be having this issue.
I was building a custom MVC in PHP when I encountered this issue.
I was able to resolve this by setting my assets (css/js/images) files to an absolute path.
Instead of using url like href="css/style.css" which use this entire current url to load it. As an example, if you are in http://example.com/user/5, it will try to load at http://example.com/user/5/css/style.css.
To fix it, you can add a / at the start of your asset's url (i.e. href="/css/style.css"). This will tell the browser to load it from the root of your url. In this example, it will try to load http://example.com/css/style.css.
Hope this comment will help you.
It is because you must have set content type as text/html instead of text/css for your server page (php,node.js etc)
I want to expand on Todd R's point in the OP. In asp.net pages, the web.config file defines permissions needed to access each file or folder in the application. In our case, the folder of CSS files did not allow access for unauthorized users, causing it to fail on the login page before the user was authorized. Changing the required permissions in web.config allowed unauthorized users to access the CSS files and solved this problem.
I have the same exact problem and after a few minutes fooling around I deciphered that I missed to add the file extension to my header. so I changed the following line :
<link uic-remove rel="stylesheet" href="css/bahblahblah">
to
<link uic-remove rel="stylesheet" href="css/bahblahblah.css">
Using React
I came across this error in my react profile app. My app behaved kind of like it was trying to reference a url that doesn't exist. I believe this has something to do with how webpack behaves.
If you are linking files in your public folder you must remember to use %PUBLIC_URL% before the resource like this:
<link type="text/css" rel="stylesheet" href="%PUBLIC_URL%/bootstrap.min.css" />
In case anyone comes to this post and has a similar issue. I just experienced a similar problem, but the solution was quite simple.
A developer had mistakenly dropped a copy of the web.config into the CSS directory. Once deleted, all errors were resolved and the page properly displayed.
I came across the same issue whilst resuming work on a old MEAN stack project. I was using nodemon as my local development server and got the same error Resource interpreted as stylesheet but transferred with MIME type text/html. I changed from nodemon to http-server which can be found here. It immediately worked for me.
This occurred when I removed the protocol from the css link for a css stylesheet served by a google CDN.
This gives no error:
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Architects+Daughter">
But this gives the error Resource interpreted as Stylesheet but transferred with MIME type text/html :
<link rel="stylesheet" href="fonts.googleapis.com/css?family=Architects+Daughter">
I was facing similar issue. And Exploring solutions in this fantastic Stack Overflow page.
user54861 's response (mismatching names in case sensetivity) makes me curious to inspect my code again and realized that "I didnt upload two js files that I loaded them in head tag". :-)
When I uploaded them the issue runs away ! And code runs and page rendered without any another error!
So, moral of the story is don't forget to make sure that all of your js files are uploaded where the page is looking for them.
I came across the same issue with a .NET application, a CMS open-source called MojoPortal. In one of my themes and skin for a particular site, when browsing or testing it would grind and slow down like it was choking.
My issue was not of the "type" attribute for the CSS but it was "that other thing". My exact change was in the Web.Config. I changed all the values to FALSE for MinifyCSS, CacheCssOnserver, and CacheCSSinBrowser.
Once that was set the web site was speedy once again in production.
Had the same error because I forgot to send a correct header a first
header("Content-type: text/css; charset: UTF-8");
print 'body { text-align: justify; font-size: 2em; }';
I encountered this problem when loading CSS for a React layout module that I installed with npm. You have to import two .css files to get this module running, so I initially imported them like this:
#import "../../../../node_modules/react-grid-layout/css/styles.css";
but found out that the file extension has to be dropped, so this worked:
#import "../../../../node_modules/react-grid-layout/css/styles";
If nodejs and using express
the below code works...
res.set('Content-Type', 'text/css');
I started to get the issue today only on chrome and not safari for the same project/url for my goormide container (node.js)
After trying several suggestions above which didn't appear to work and backtracking on some code changes I made from yesterday to today which also made no difference I ended up in the chrome settings clicking:
1.Settings;
2.scroll down to bottom, select: "Advanced";
3.scroll down to bottom, select: "Restore settings to their original defaults";
That appears to have fixed the problem as I no longer get the warning/error in the console and the page displays as it should. Reading the posts above it appears the issue can occur from any number of sources so the settings reset is a potential generic fix.
Cheers
If you are serving the app in prod make sure you are serving the static files with service worker. I had this error when I was serving only static subfolder of React build on Django (without assets that have styles)