Running an angular project with node.js - javascript

I've an angular project that I can run without issues with ng serve. But I have to use node.js to have access to a DB.
I've created a file server.js:
var express = require('express');
var path = require('path');
var app = express();
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './','index.html'));
});
var port = process.env.PORT || 4800;
app.listen(port, (req,res) => {
console.log(`RUNNING on port ${port}`);
});
And this index.html file:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngNode</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script>
<script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script>
</body>
</html>
When I run the server.js file I got the RUNNING on port 4800 but when I open the browser I got nothing but a blank page and no error. I tried to add a Hello World before the <app-root></app-root> and it's been displayed on the window but that's all.
I don't have any error on my console or on the browser so I don't know how to correct it.
Thank you

The problem is that your angular application is not running under 4800 but under 4200 (by default) so although you are not getting js errors you are probably getting 404 in the request tab.
You need to setup a proxy in your angular application (for development see https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/) or, in case you want to deliver the files from the express server, you need to compile the app, deploy the bundled version and configure your express to correctly deliver the files you need depending on the path.

Related

App works fine on 127.0.0.1, but not when accessed from another device

I managed to publish my app with nodejs and I am able to access it from devices in my network (mind you its going to be a local app only). It is an app that is used to control other hardware connected to my network.
The problem I am having right now is that, the app is working fine when I open it from 127.0.0.1:8081 from my local PC on which it is hosted, but if I attempt to open it from another device (or even from the hosting PC itself) by using the IP of the hosting PC 192.168.z.z:8081, the javascript files dont work and here is what I mean.
I have a config.js file which holds configuration data that my app needs to work, like IP of the device that I am controlling.
var config = {
URL: '192.168.0.2',
}
Then I have a Model.js file that has SetData and GetData which are both dependent on config.URL to execute their AJAX requests, however config.URL stays null, its hardcoded and still a null!
When I run the app and do config.URL in the console, I get null, even if I manually set it in the console config.URL = '192.168.0.2', and then try to invoke Model.SetData..... or Model.GetData... they still dont see it, they still are attempting to send a request to http://null/......
Here is my node code:
const express = require("express");
const app = express();
const port = 8081
app.use(express.static('public'))
app.use('/css', express.static(__dirname + '/public/css'));
app.use('/js', express.static(__dirname + '/public/js'));
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
I have tried with and without the app.use(/css and /js lines of code, no change
Here is how my JS is added to my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Robot Stuff</title>
<script type="text/javascript" src="./js/jquery-3.5.0.js"></script>
<script type="text/javascript" src="./assets/scripts/main.js"></script>
<script type="text/javascript" src="./js/easy-numpad.js"></script>
<script type="text/javascript" src="./js/jquery-modal.js"></script>
<script type="text/javascript" src="./js/Model.js"></script>
<script type="text/javascript" src="./js/UI.js"></script>
<script type="text/javascript" src="./js/config.js"></script>
<link href="./css/main.css" rel="stylesheet" type="text/css" >
<link href="./css/easy-numpad.css" rel="stylesheet" type="text/css" >
Again, if I open that app from http://127.0.0.1:8081, or if I directly go and double-click on my index.html file, it all works just fine, but when I use the actual IP of the PC to access it remotely, then it breaks.
I dont want to overcomplicate it more than necessary, I am simply trying to use node explicitly to make the app available on my network, nothing more.
You need to allow cross origin policy in your server script.
That will enable you to accept request headers from your other devices also.
npm i cors --save
or alternatively you can follow this guide
Enable CORS in nodejs
Check with netstat -nlp if your server is working on 0.0.0.0 or 127.0.0.1. This could possibly be one of the issue for non-accessibility outside localhost.

How do i fix MIME type error? ubuntu vs windows

I have an application which I've built on my laptop booted in too windows 10. The problem is when I boot into ubuntu and start the server with nodemon and check the website in chrome I get this error and the scripts won't run.
"Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.".
The thing is it works when I'm running chrome on windows but not chrome on ubuntu.
The project is made with node and express. Heres the code to serve the files.
const express = require('express');
const app = express();
app.use(express.static('public'));
app.get('/*', (req, res) => res.sendFile(__dirname + '/public/index.html'));
app.listen(3000, () => console.log('Listening on port 3000'));
my index.html looks like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./css/style.css">
<script type="module" src="./js/index.js" defer></script>
<title>Mina Kontakter</title>
</head>
<body>
</body>
</html>
I really have no clue what to do. I find it really weird that it works when I boot into windows but not ubuntu.

nodejs config on subdirectory

I have a sub-domain and I publish my server.js on this directory. everything work fine. but I want to running my server.js inside a directory(because I want to run my react.js project on sub directory). for example:
web.example.com/sr
web is my subdomain and sr is my directory.
but my routes not worked at all:
web.example.com/sr/user/1
I got this error message:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /sr/user/1</pre>
</body>
</html>
Should I make any changes or is there any config to do this?
You can't do deployment-level configs to serve your react app to the subdir /sr. Every call to your.domain.com/sr/* will end up in your server and pass /sr/* to it (and not simply /*.
You'll have to code your server to serve your React app. If you bundle your react app to index.html and bundle.js, you'll have to write something like this (if you're using express, which you probably do):
app.get(/\/sr\/\.js/, (req, res) => res.sendFile(`${__dirname}/bundle.js`));
app.get(/\/sr\/*/, (req, res) => res.sendFile(`${__dirname}/index.html`));
If you're using react-router, you'll have to set it up too so as to take into account the leading /sr in your URL.

I am having issues getting the src tags for my js and css files to work

I am trying to work on a sample web application using HTML5 boostrap express js angular and jquery. I have been fighting with the source tags to the js and css files I am trying to include and just cannot get them to work unless I use one that is hosted online. If any one has some spare time here is what my header code looks like
index.html
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="/bower_components/bootstrap/dist/css/bootstrap.css"/>
<script type="text/javascript" src="/bower_components/bootstrap/dist/js/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
------------------------------------------------------------------------------------
app.js
var express = require('express');
var path = require('path');
var app = express();
//config
app.set('views', __dirname + '');
app.engine('html', require('ejs').renderFile);
//routes
app.get('/',function(req,res){
res.render('index.html')
});
//server
app.listen(1337,function(){
console.log('ready on port 1337');
})
This is a screenshot of of my file stucture
My server is running in the app.js located in the root folder. I have tried many variations of ../ and no slash and even the ~ to attempt to get this to operate. Thank you for your time in advance.
EDIT So while I have been messing around I realized if I open the index.html file without running it on my express server it works just fine. I have updated the code portion above to include my app.js.
SOLVED
A big thanks to suchit,dfsq,and Anubhav.
So since I was using express I needed to tell express how to properly path to my static src files "aka the js and css" inside of my app.js. So the answer I provide is only relevent if you are running your application on an express server. I will provide the code that was added to my app.js file and to my index.html file to come to a solution.
app.js
app.use(express.static(__dirname + '/bower_components'));
--------------------------------------------------
index.html
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="/bootstrap/dist/css/bootstrap.css"/>
<script type="text/javascript" src="/bootstrap/dist/js/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
Sincerely,
Fred K
Add app.use(express.static(__dirname + '/bower_components')); to app.js (it is a configuration) then link to the static files can be written as <script type="text/javascript" src="/bootstrap/dist/js/bootstrap.js"></script>
This assumes all your static files such as javascript and CSS files reside in your /bower_components folder.
The statement instructs the app to make /bower_components the root for all the static files.
app.js now looks like
var express = require('express');
var path = require('path');
var app = express();
//config
app.set('views', __dirname + '');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/bower_components'));
//routes
app.get('/',function(req,res){
res.render('index.html')
});
//server
app.listen(1337,function(){
console.log('ready on port 1337');
})

Express not rendering bootstrap

I'm just starting out with Express and I'm trying to figure out why, when I run my app, the Bootstrap font isn't rendered (it's showing the text in simple Times New Roman). I'm pretty sure I'm using the correct paths because when I open my index.html in my browser the font is rendered correctly. I also tried this with a Bootstrap navbar, and Bootstrap doesn't appear to work correctly when I try to run it through Node, but it works, again, when I view the HTML file in my browser independently. Changing the path of the Bootstrap directory to "/public/bootstrap..." causes it to render incorrectly both ways. How do I fix this?
index.html:
<html>
<head>
<title>X</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../public/bootstrap/css/bootstrap.min.css" type="text/css" rel="stylesheet" media="screen">
</head>
<body>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<div class="container">
<h1>Under Construction</h1>
<p>This website is under construction. Come back soon!</p>
</div>
</body>
</html>
web.js (my main app file):
var express = require('express')
var app = express()
app.set('view engine', 'ejs')
app.engine('html', require('ejs').renderFile)
app.get('/', function(req, res) {
res.render('index.html')
})
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
})
1) bootstrap and express have nothing to do with each other. Bootstrap runs on the client side completely, and express is a server middleware lib over node.js
2) Why are you serving bootstrap yourself? better use a CDN :
http://www.bootstrapcdn.com
http://hostedbootstrap.com/
3) if you insist on serving it yourself add a static directory so that express can serve static files (adding a static will also serve you when you try and serve js / css for yoursite but still prefer to serve bootstrap from a CDN.
app.use(express.static(path.join(__dirname, 'public')));
then no need to use public, just use the root path right to your css:
bootstrap/css/bootstrap.min.css
i.e.
<link href="../public/bootstrap/css/bootstrap.min.css" type="text/css" rel="stylesheet" media="screen"
You need an actual static middleware. Express itself doesn't do anything by default.
app.use(express.static(__dirname + "/public"));
Don't use "public" in the paths in your HTML. That's the directory where the static assets live, but from the browser's perspective that's the root. And don't use relative paths, either
.
<link href="/bootstrap/css/bootstrap.min.css" type="text/css" rel="stylesheet" media="screen">

Categories

Resources