Webpage cannot find certain files - javascript

I am building a simple sandbox/practice style website on heroku I am trying to learn nodejs and I am learning Angular. After much hit and miss I got the server to load my home.html page, however it cannot seem to find my vendor scripts. Such as my angular, contollers, and some images/css.
The path I have setup for angular is: <script src="/vendor/angular.min.js"></script>
<script src="/controller.js"></script>
This is coming from a localhostconnection by the way, so http://localhost Here is an example of what my simple index.js in node looks like:
var express = require("express");
var app = express();
app.set("port", (process.env.PORT || 5000));
app.engine('html', require('ejs').renderFile);
app.set('views engine', 'html');
app.use(express.static(__dirname + "/public"));
app.get("/", function(request, response) {
response.render("home.html");
});
app.listen(app.get("port"), function() {
console.log("Node app is running at localhost:" + app.get("port"));
});
this is located in the root of the webfiles and it points to a views folder which includes my home.html (how I got my home page to finally load) However it still says it cannot find my vendor scripts.
These are located inside their own vendor folder that is in the root folder, and the views folder is also its own folder in the root folder the setup is like so:
-views
---home.html
-vendor
--some vendor folders(bootstrap etc)
---angularjs.js and other vendor scripts
I am sure I am missing something simple here, but I am a beginner with nodejs and still learning at this point. Thank you ahead of time for the help, and let me know if I can offer anymore information.

Related

Express GET request works on local server, but not on hosted site

I am working to flesh out my portfolio site, and I am trying to add a link in a project block to a recent web project. I developed this side project in isolation from my portfolio site documents, but now that it's ready to show, I want to host it off of the same domain as my portfolio.
The problem I'm having is that the get request to the side project page won't show the index.ejs file. The format of the code at this moment represents just a simple test to get it to work at a basic level. This code works just fine on a local server, but when uploaded to run off my droplet, it shows the "Cannot GET /page" error.
Both my index.html and index.ejs files are hosted in a views folder. I have tried multiple variations of the filepath for the index.ejs file to no avail. Any help would be much appreciated!
server.js file
const express = require('express');
const app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/page', function(req, res) {
res.render(__dirname + '/views/index.ejs');
});
const listener = app.listen(8080, function() {
console.log('Your app is listening on port ' + listener.address().port);
});
html file
<div class="project-tile">
<form action="/page" method="GET">
<button type="submit">Link</button>
</form>
</div>

Can I use home.ejs instead of index.html?

The problem is, that when I'm deploying my website with FileZilla, I get a 403 forbidden. After a bit of searching for answers, it seems like it's because I don't have an index.html, but I'm using home.ejs instead. Can I set up my project, so it uses the home.ejs instead of an index.html?
I've made a one page website (which is going to be expanded to more pages), that works as a resume and I now need to deploy it to my domain.
It is the 2nd version of my website, as I've been making it alongside a web development course I've been taking. The first version was made from html, css and Bootstrap, as a static page. The new version includes JavaScript, node.js, express and ejs.
My file structure looks like this
Project:
node_modules
public
css
images
views:
partials
header.ejs
footer.ejs
home.ejs
app.js
package-lock.json
package.json
Everything works when I deploy it locally (localhost:3000). I am pretty new to the whole web development thing. Even though the course I took was really good, it didn't talk about deploying a website to your own domain name.
Here is the app.js file:
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;
var $ = require("jquery")(window);
const app = express();
app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function(req, res){
res.render("home", {years: years, comp: comp, placing: placing});
});
app.listen("3000", function(){
console.log("Server started on port 3000");
});
EDIT:
I needed a webserver to install node.js on.

Resolving dependencies in express server

I am having some trouble resolving dependencies on my express server.
Here is my project structure
Calculator
--dist
----app
-------calculator.js
-------server.js
--node_modules
--src
----app
--------calculator.js
--------server.js
----public
--------calculator.css
--------calculator.html
----.babelrc
----.gitignore
----package.json
Here is my server.js code
const express = require('express');
const app = express();
const path = require('path');
app.get('/', (req, res) => {
res.sendFile(path.resolve('./src/public/calculator.html'));
});
app.use(express.static(__dirname + '../../src/app/public'));
app.use(express.static(__dirname + './'));
app.listen(3000, () => {
console.log(__dirname);
console.log("Listening on port 3000");
});
The reason I have a dist folder and a src folder is because I am compiling my JS from ES6 from the src folder to ES5 within the app folder using Babel.
However, when I launch my node server, my html is not able to load the css file and JS file. I am using these paths to load each respectively from the calculator.html file
<link rel="stylesheet" type="text/css" href="./calculator.css">
<script type="text/javascript" src="./calculator.js"></script>
I am sure I am missing something about the way files are served on a localhost. Would appreciate the error being pointed out.
It looks like on line 9 in server.js:
app.use(express.static(__dirname + '../../src/app/public'));
you're going from the app folder up to src, up to the root, back down into src, back into app, and then trying to go down into public. However by your project structure diagram, public isn't inside app but rather beside it. You'd want something more like app.use(express.static(__dirname + '../public')); In addition, I'd recommend using the path module that's built into Node. It'll make sure you don't have mistakes in path creation.
EDIT: Sorry, that was incorrect. I didn't see that you were transpiling your server code as well. You'll want to use these lines, which should fix both:
app.use(express.static(__dirname + '../../src/public'));
app.use(express.static(__dirname));
This is assuming you run the server.js file present in dist/app and not the one in src/app.
Alright, this worked for me although I'm not a 100% sure why exactly.
I set my express static file delivery to the following
app.use(express.static(__dirname + '/../../src/public'));
app.use(express.static(__dirname));
My __dirname was shown to be Calculator/dist/app so changing the src attributes for the CSS and JS in the HTML file to this worked
<link rel="stylesheet" type="text/css" href="./calculator.css">
<script type="text/javascript" src="./calculator.js"></script>
I am assuming this works because I set my express static folder to look inside the /src/public folder and since my current directory was the /dist/app folder, I could serve the JS file directly from there?
Try one of these ...
app.use(express.static(__dirname + '/./src/app/public'));
app.use('/', express.static(__dirname} + '/./src/app/public')); // __dirname doesn't include the ending back slash, I think?
The first will always look in your static directory, and the second will look in your static directory for '/' and below. See https://expressjs.com/en/4x/api.html#app.use for more.
And then ...
Change your HTML so the src attributes will be '/calculator.css', etc

How to render HTML view with parameters using ExpressJS (on the home/root view)?

I'd like send a parameter and render a html file when the user go to the home page of my app.
Here is what I did so far:
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
console.log('Hi !'); // never displayed
res.render('index', { foobar: 'foobar'});
});
The HTML is properly rendered (probably due to express.static) but app.get('/') seems to be never called so I can't return the variable.
How can I return a variable from a call to '/' with the static HTML page public/index.html?
My ultimate goal is to be able to use foobar in my JS without any additional call to the server. Could you help me to achieve this?
If you have a file named index.html in your public/ directory, express.static() will return that file if the url / is requested, so your route handler will never get passed the request.
Generally, templates are stored in a separate directory than static (public) resources. Express, by default, will look for templates in the ./views directory (unless you tell it otherwise) so if you move your index.html to there it will get rendered by EJS (but see below), and you can use your parameters in it.
Since EJS will by default look for files ending with a .ejs extension, if you want to keep on using .html, you need to set up Express as follows:
var ejs = require('ejs');
...
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);
This tells Express to look for files with extension .html in the ./views directory, and to render those files using EJS.
var express = require('express');
var router = express.Router();
router.get('/index',function(req,res){
res.sendFile(path.resolve('./public/index.html'));
});
module.exports = router;

Include css to html using express

I am trying to include a css sheet to my simple html page.
I am using parse.com hosting to host a dynamic webpages that uses express.
There is a ton of answers on this questions, but none of them seemed to work for me.
I am trying to include my css file from my .ejs page with this line of code
<link rel="stylesheet" type="text/css" href="css/content.css" />
I copyed my css folder inside the public floder
The most suggested answer is to add this line of code:
app.use(express.static(__dirname + '/public'));
but it did not work.
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
// Global app configuration section
app.set('views', 'cloud/views'); // Specify the folder to find templates
app.set('view engine', 'ejs'); // Set the template engine
app.use(express.bodyParser()); // Middleware for reading request body
// This is an example of hooking up a request handler with a specific request
// path and HTTP verb using the Express routing API.
app.get('/content/:id', function(req, res) {
res.render('content', {message: "hi"});
});
I am following this guide to set up express:
https://www.parse.com/docs/hosting_guide#webapp-started
when I try to deploy my code, I get this error "Update failed with Could not load triggers. The error was ReferenceError: __dirname is not defined"
What am I doing wrong here?
After looking into this problem for some more time, I read this on parse.com website.
"our Express app can sit side-by-side with any static content you deployed from your public folder. When a request goes to a URL of your subdomain, Parse will first look for a matching file in the public directory. If there is no match, then Parse will invoke any Express request handlers that you have registered in Cloud Code. If there is still no match, Parse will render a "404 Not Found" page."

Categories

Resources