at last time I have learn use AngularJS and NodeJs, but I have a few problems.
First:
I'd like loading.. for instance index.html or other file, now I do this manual and simplest how I can, but even then I have problem with type file which are include in index.html I receive:
Resource interpreted as Stylesheet but transferred with MIME type text/html:...
How can I correct this ?
below code.
'use strict';
var http = require('http');
var fs = require('fs');
var mysql = require('mysql');
var render = function(response, fileName, code, httpCode){
var code = code || 'utf8';
var httpCode = httpCode || 200;
fs.readFile(fileName, code, function(err, data){
if(err) { return console.log(err); }
response.writeHead(httpCode, {'Content-type': 'text/html; charset='+code});
response.write(data);
response.end();
});
};
http.createServer(function(req, res){
render(res, 'index.html');
}).listen(9999, '127.0.0.1');
console.log('Server running');
html:
<!doctype html> <html class="no-js"><head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type='text/css' href="styles/main.css">
</head><body></body></html>
Can I use nodejs server with gruntjs ? if yes, how I can do it ?
Do somebody know any tutorial only angular + node ? it's mean I know quite good angularJS, but I can't use it with nodeJS..
The problem is that your browser requested a css file and you returned a file with the MIME type text/html. You would have to handle all the possible types of files (js, html, txt, css, ...).
I would recommend you to use an existing module like express, which will save you a lot of time. After installing express, initalize a static file server by doing following:
server.use(express.static(__dirname + '/public'));
This is how my folder structure look like of Angular JS + Node JS (with Express JS)
ProjectTitle
|_app
|_bower_components
|_images
|_scripts
|_styles
|_views
|_index.html
|_favicon.ico
|_routes
|_test
|_.bowerrc
|_.jshintignore
|_.jshintrc
|_bower.json
|_Gruntfile.js
|_package.json
|_README.md
|_server.js
3 imp things to notice here
/app - contains angular static app including all its dependant styles, scripts & images
/app/script - angular javascript files
/server.js - node js web server code, here is sample code
var express = require('express'),
http = require('http'),
path = require('path');
var app = express();
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.static(path.join(__dirname, 'app'))); // here you are mentioning which directory should be static directory for the project, in this case 'app'
app.use(express.favicon());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
Start node js server using
$ node server.js
It will start express server, and you can access it by typing in browser window
localhost:3000
It will be good to look at Yeoman and install Angular Generator. This is just to setup proper angular js project without error. If you have your own structure thats fine.
Related
I have deployed the nodejs application with aws eb deploy, client.js is not getting loaded in index.hbs files and returning 404 error (Failed to load resource: the server responded with a status of 404 (Not Found))
I have tried all the step in the internet and wasted two days for this.
Can any one please help me here ? I am doing anything wrong here?
I have tried the solution in this stackover flow page Elastic Beanstalk Static Folder 403 Error but no luck
staticfiles.config(NodejsPlayGround.elasticbeanstalk\staticfiles.config) file
option_settings:
aws:elasticbeanstalk:container:nodejs:staticfiles:
/public: public
index.hbs(NodejsPlayGround\views\index.hbs) file
<!DOCTYPE html>
<html>
<head>
<title>NodeSeverTest</title>
<script src="js/client.js"></script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
server.js(NodejsPlayGround\server.js) file
'use strict';
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
const views_path = path.join(__dirname, 'views');
const static_path = path.join(__dirname, 'public')
app.set('view engine', 'hbs');
app.set('views', views_path);
app.get('', (req, res) => {
res.render('index', {
title: 'Weather App',
name: 'ArunKumar Arjunan'
}
);
});
app.listen(port, () => {
console.log('server started on port ' + port);
});
client.js(NodejsPlayGround\public\js\client.js) file:
console.log('client side java script file is loaded');
client.js file needs to be loaded in index.hbs file
I find that contrary to the AWS documentation on this, the folder path also needs a leading slash — i.e. you map /public to /public (not just public), or /static to /static (not just static).
I figured this out by inspecting the nginx error log and conf files on my EB instances, and both showed that it was looking for my static files in /var/app/currentstatic instead of /var/app/current/static.
I am learning Mean.js stack, and try to build an app. I have installed Express, and it works. When I tried to configure my static file ( html, js, images, etc.), then things broke.
Here are my files:
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + "public"));
app.listen(3000);
console.log('Server running on port 3000');
My html file is very simple :
<!DOCTYPE>
<html>
<head>
<title>Contact List App</title>
</head>
<body>
<h1>Contact List App</h1>
</body>
</html>
So when I start the server : node server.js, and then I type http://localhost:3000/ in the browser, I get the "Cannot Get" error.
Where is the problem?
__dirname doesn't have a trailing slash, so you need to provide one yourself when building the static root:
app.use(express.static(__dirname + "/public"));
^ this needs to be there
You need to make sure the route exists. Also, it is a better practice to use path for joining strings. Also, make sure the directory public exists and the file index.html is inside that folder.
var path = require('path');
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index.html');
});
app.listen(3000);
console.log('Server running on port 3000');
I want to use HTML5 app cache in my MEAN app but I can't make it work in Firefox 36. It works in Chromium as expected. This is my file structure:
client
app.js
manifest.appcache
views/
index.html
about.html
server.js
index.html:
<!DOCTYPE html>
<html manifest="/manifest.appcache">
<head>
<meta charset="UTF-8">
</head>
<body>
About
</body>
</html>
manifest.appcache:
CACHE MANIFEST
#0
CACHE:
views/about.html
app.js
server.js:
var http = require("http");
var express = require("express");
var app = express();
app.get("/manifest.appcache", function (req, res) {
res.set("Content-Type", "text/cache-manifest");
res.set("Cache-Control", "no-store, no-cache");
res.set("Expires", "-1");
res.sendFile("/client/manifest.appcache", {root: __dirname});
});
app.get('/', function (req, res) {
res.sendFile('/client/views/index.html', {root: __dirname});
});
app.use(express.static(__dirname + '/client', { maxAge: 31557600000 }));
app.listen(8080);
When I go to localhost:8080, Firefox successfully fetches the manifest (which is not visible in the network tab of dev tools) but it does not store the files in the app cache (Preferences - Advanced - Network shows 0 bytes). It loads them from the standard system cache (I get 304).
I suspect that my routing somehow breaks the links in manifest.appcache but I had to prevent the manifest to be cached itself. I'm not an expert on Node.js and I'm confused by the fact that Chromium and Firefox behave differently. Any help will be appreciated.
I have a node.js server running with less-middleware. From my understanding, it compiles on the fly and places the css file in the destination/same(if not specified) folder.
My problem is I'm getting a 404 error on the get request for the css file:
Err: GET http://webserver/public/less/blog-reset.css 404 (Not Found)
Here is what I'm working with:
web.js
//requiring dependencies
var express = require("express");
var logfmt = require("logfmt");
var lessMiddleware = require('less-middleware');
var hogan = require('hogan-express');
var path = require('path');
//all environments
var app = module.exports = express();
var port = Number(process.env.PORT || 5000);
app.use(logfmt.requestLogger());
app.use(lessMiddleware(path.join(__dirname,'public')));
app.use(express.static(path.join(__dirname,'public')));
app.set('layout',path.join(__dirname,'src','views','blog-layout'));
app.enable('view cache');
app.engine('.html',hogan);
//page routing called after env loads
require('./src/router');
//listening port
app.listen(port, function() {
console.log("Listening on " + port);
});
blog-layout.html
<head>
<title>EpiBlog</title>
<link href='/public/less/blog-reset.css' rel='stylesheet' type='text/css'/>
</head>
<body>
{{{yield}}}
</body>
directory layout
ROOT
public
less
src
web.js
Versions
less-middleware v0.2.1-beta
express v4.0.0
What I've tried:
using app.use(lessMiddleware)({ src: __dirname + '/public' })); (apparently the old way of doing it)
using app.use(lessMiddleware(path.join(__dirname,'public','less')));
moving app.use(express.static(path.join(__dirname,'public'))); from web.js to router.js
toying with different paths
moving contents of router.js to web.js
specifying the destination using
this:
app.use(lessMiddleware(path.join(__dirname, 'source', 'less'), {
dest: path.join(__dirname, 'public')
}));
the problem was:
<link href='/public/less/blog-reset.css' rel='stylesheet' type='text/css'/>
should have been:
<link href='/less/blog-reset.css' rel='stylesheet' type='text/css'/>
i read that:
link(rel='stylesheet', type='text/css', href='css/styles.css')
was paired with directory structure:
myapp
+-public
+-css
+-styles.less
which led me to believe that this call:
app.use(express.static(path.join(__dirname,'public')));
makes the request assume /public/ is the parent so i was being redundant calling /public/less/blog-reset.css
reference was found here: express.js less compiler: can not get work
I use this function to send html file to client, but in client I get nothing (blank page) without error. Something I wrong?, please help?
var express = require('express');
var fs = require('fs');
var app = express();
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express);
app.get('/test', function(req, res) {
fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
res.send(text);
});
var port = process.env.PORT || 80;
var server = app.listen(port);
console.log('Express app started on port ' + port);
My test.html file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style something here </style>
<title>Test</title>
<script src="..."></script>
</head>
<body>
<div> Somthing here </div>
<script type="text/javascript">
//something here
</script>
</body></html>
Try your code like this:
var app = express();
app.get('/test', function(req, res) {
res.sendFile('views/test.html', {root: __dirname })
});
Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.
You don't need the app.engine line, as that is handled internally by express.
you can render the page in express more easily
var app = require('express')();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.get('/signup',function(req,res){
res.sendFile(path.join(__dirname,'/signup.html'));
});
so if u request like http://127.0.0.1:8080/signup that it will render signup.html page under views folder.
After years, I want to add another approach by using a view engine in Express.js
var fs = require('fs');
app.get('/test', function(req, res, next) {
var html = fs.readFileSync('./html/test.html', 'utf8')
res.render('test', { html: html })
// or res.send(html)
})
Then, do that in your views/test if you choose res.render method at the above code (I'm writing in EJS format):
<%- locals.html %>
That's all.
In this way, you don't need to break your View Engine arrangements.
The "../" is considered malicious and will result in ForbiddenError: Forbidden at SendStream.error... exception.
The way to go is using a path module:
var path = require('path');
res.sendFile(path.resolve('views/auth/success.html'));
var app = express();
app.get('/test', function(req, res) {
res.sendFile(__dirname + "/view/test.html")
});
Here __dirname, gives you the current path where your files are saved. So in res.sendFile(), we first tell our current location by __dirname + (then we locate the specific file which should we shown on the home page i. e ) "vies/test.html".
Follow this simple process and send html file ->
res.sendfile("views/home.html"); // don't use capitla latter F with sendFile you must be use small letter f
example : sendfile();