Can i connect an already created angular project with nodejs(express) - node.js

I already created an angular website in which i have done routing and connected to firestore. but now i want a middleware connection because i want the values scanned by RFID scanner(Rasberry PI)to get stored in firestore.
So can i connect this angular project with node as per now or do i need to rebuild my app?
I already tried to connect using node js but when i am running the server the screen is blank and only title is displayed
------IN SERVER.js---------
const express = require('express');
const path = require('path');
const http = require('http');
// const bodyParser = require('body-parser');
// const morgan = require('morgan');
const proxy = require('express-http-proxy');
// const cors = require('cors');
const request = require('request');
const app = express();
// app.use(cors());
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3001';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on ${port}`));
-------IN DIST/index.html --------
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Miracle Bus Track</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
<app-root></app-root>
</body>
</html>

The answer is 'yes', as client side JS UIs are usually decoupled from backend and can be hosted wherever.
However, your specific issue sounds like a code/build issue that Stackoverflow won't be a good place to sort out. One thing I see is you don't reference a tag anywhere for the angular javascript so you should start there.

Looking at the scenario you mentioned, I would like to suggest you some different approach to handle this.
I would suggest you to use Google Cloud function https://cloud.google.com/functions/ instead of creating your own nodejs server.
Cloud functions are serverless functions run on nodejs server.
I am suggest this because you are already using Firestore.
I am suggesting so e architectural changes in your project.
Google also provide IOT module. That may help you more to cuumunicate to your Raspberry Pi.

Related

How do I get HTML-linked JS files to use Require?

I am an express newbie, and I am trying to get a static HTML page to read details from a file in Express.
Initially I had a static HTML page where users could register where they were based on a particular day (as we are now rather flexible with working arrangements). However, it became apparent that I needed to store the current situation somewhere each time someone updated their details (and retrieve it when someone else signs on), so I did some investigating and came up with Node and Express.
I have an HTML file in the public directory, and it links to a JS file where I want to do a "fs" read.
app.js
app.use(express.static(path.join(__dirname, 'public')));
var steveRouter = require('./routes/steve');
app.use('/steve', steveRouter);
routes/steve.js
var express = require('express');
var path = require('path');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.sendFile(path.resolve(__dirname, '../public', 'steve.html'))
});
module.exports = router;
public/steve.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World : title</title>
<script src="steve.js"></script>
</head>
<body onLoad="loadUp()">
<h3>small-ish heading</h3>
</body>
</html>
public/steveHtml.js
const fs = require('fs');
function loadUp() {
alert("Ciao");
let rawdata = fs.readFileSync('student.json');
let student = JSON.parse(rawdata);
console.log(student);
alert(student.name);
}
The server starts ok, but the browser shows the message "Uncaught ReferenceError: require is not defined at steveHtml.js:1"
This is probably the wrong way of doing it, but I would love to know :
how do I get the "called" JS file to recognise the require command?
is there a better/simpler/easier way of accomplishing what I want?

Refused to apply stylesheet because its a MIME type, running off of ATOM.io onto Google Chrome

I'm a new programmer and need some help. I'm trying to launch a website and my stylesheet won't load. The error looks like this:
Refused to apply style from 'http://localhost:3000/stylesheets/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I know that there are other similar errors reported, but I am running off of Atom.io onto a Google Chrome browser. Not sure if it has anything to do with my IDE or browser but every other solution I have seen has not worked for me. I'm running node.js on the backend and this is my code:
var express = require('express'),
`app = express(),
bodyParser = require('body-parser'),
mongoose = require("mongoose"),
passport = require('passport'),
flash = require('connect-flash'),
methodOverride = require('method-override'),
LocalStrategy = require('passport-local');
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static(__dirname + "/public"));
app.set('view engine', 'ejs');
//index
app.get('/',function(req,res){
res.render('home')
})
app.listen(3000, function(){
console.log("Your personal website has started")
}); `
Can anyone help me out? My front end code looks like this as well:
<html lang = 'en'>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"></link>
<link href ='/stylesheets/home.css' rel ='stylesheet' type = 'text/css'></link>
</head>
Thanks!
Jake
Use this code in server file:
app.use(express.static(__dirname + '/public'));
Use this code in home.ejs file
<link rel="stylesheet" type="text/css" href="/css/app.css" />

Cannot load stylesheets node

I have created basic node/express server
var express = require('express');
var app = express();
var path = require('path')
var port = 8080;
app.use("/styles", express.static('../public/styles'));
app.get('/' , function( req , res ){
console.log(__dirname)
res.sendFile(path.join(__dirname,'../public/html/index.html'))
})
app.listen(port)
structure of project is simple
app
public
html
index.html
styles
javascripts
routes
server.js
html file looks very simple
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../styles/index.css">
<title> Hello world!</title>
</head>
<body>
</body>
</html>
yet it still complains
GET http://localhost:8080/index.css 404 (Not Found)
Yet my paths should be correct , i looked up this problem and every answer is about using
app.use("/styles", express.static('../public/styles'));
so browser know how to redirect when looking for a stylesheets. Which does not work for me.
Could anybody help with this common problem?
Thanks!
Not clear what your project structure is. It's more common to have app.js in your project directory contain the basic express server and if you have complicated routing, do that in routes/server.js
So you could change your project structure:
app.js (main file)
public
index.html
styles
index.css
javascripts
routes
server.js --not needed?
If that's the case, change app.js to:
var express = require('express');
var app = express();
var port = 8080;
//use static folder public to serve everything up
app.use(express.static('./public/'));
app.listen(port)
In index.html, to include index.css:
<link rel="stylesheet" href="/styles/index.css" >

How to share common function between server and client using node.js

Following are the structure of my application
Inside prototype.js file i have following code:
(function(exports) {
exports.foo = function() {
return 'bar';
};
})((typeof process === 'undefined' || !process.versions) ? window.common = window.common || {} : exports);
app.js contains
var express = require('express'),app = express(),server = require('http').createServer(app),io = require('socket.io').listen(server),port = 3000,path = require('path');
var common = require('common/prototype');
console.log(common.foo());
// listening to port...
server.listen(port);
//Object to save clients data
var users = [];
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.sendfile('/public/index.html');
});
index.html contains
<!doctype html>
<html lang="en">
<head>
<title>Socket.io Demo</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="/common/prototype.js"></script>
<script>
alert(window.common.foo()); //This line will gives me an error TypeError: window.common is undefined
</script>
</body>
</html>
Now i would like to print
Hello, I am bar from server and client as well.
Now i am able to print from server side using following line
var common = require('common/prototype');
console.log(common.foo());
But could not able to show alert on client side. could you please help me to find the root cause for the issue.
The root cause is that when you do <script src="/common/prototype.js"></script> in your HTML the file won't be fetched because the Express static middleware is only looking for files under your public folder.
A quick way to test this is to copy your prototype.js to your javascript folder inside public. Then update your script tag to reference the file as follows <script src="/javascripts/prototype.js"></script>
The thing to remember is that the JavaScript files that live under node_modules are not automatically available to the browser.

Can't get stylesheet to work with ejs for node.js

I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.
app.js
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');
var PORT = 8080;
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('board.ejs', {
title: "anything I want",
taco: "hello world",
something: "foo bar",
layout: false
});
});
app.listen(PORT);
console.log("Server working");
The ejs file is in a directory views/board.ejs
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='../styles/style.css' />
</head>
<body >
<h1> <%= taco %> </h1>
<p> <%= something %> </p>
</body>
</html>
and style.css is in a styles/style.css directory relative to app.js
p {
color:red;
}
I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.
Declare a static directory:
app.use(express.static(__dirname + '/public'));
<link rel='stylesheet' href='/style.css' />
in app.js:
you must first declare static directory
app.use("/styles",express.static(__dirname + "/styles"));
in ejs file :
<link rel='stylesheet' href='/styles/style.css' />
Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory = express.static(publicDirectoryPath);
app.use(staticDirectory);
and my folder structure was like
The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.
Above example was for only one static path. For multiple static path you can use the code in the below
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory = express.static(publicDirectoryPath);
const cssDirectory = express.static(cssDirectoryPath);
app.use(staticDirectory);
app.use('/css/',cssDirectory);
And my generic HTML file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>
To set the entry point for your application dependancies like css, img etc add below line into your server.js (or which ever being used).
app.use(express.static(__dirname + '/'))
This tells to get css files from current directory where server.js is present. Accordingly you can define relative path of css in html file.
With Express 4, you can easily set this up by using the following within your app.js file.
app.use('/static', express.static(path.join(__dirname,'pub')));
Place this early in your file, after you created your require constants, and declared your express app.
Its declaring a static directory, with the help of the path object, allowing you to have a place where all of your front-end resources are available. It's also giving it a virtual directory name (/static) that can be used on the front of the site, instead of the physical name you see within your project (/pub).
In your template you can do something like this in your head
<link rel="stylesheet" href="/static/css_bundle.css"/>

Resources