AJAX (Get, Express, Node JS) to retrieve JSON & HTML data - html

I'm working on a web development project where I can retrieve JSON & HTML data from JS file by using AJAX, Get, Express and Node JS.
When the user clicks on one of the lists, I want the JSON & HTML data to show up in my HTML file. I created all the templates, but for unknown reason it's not working properly..
HTML
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<link rel="stylesheet" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>J MEDICAL | SURREY</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" id = "title" href="#">J MEDICAL</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarScroll">
<ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">HOME</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">MEDICATION</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarScrollingDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
ABOUT
</a>
<ul class="dropdown-menu" aria-labelledby="navbarScrollingDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">RESOURCES</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div class = "container">
<div id = "question"><h3>INFORMATION</h3></div>
<div id = "faq">
<ul id = "questions">
<li>CLINIC OPENING</li>
<li>COVID-19 VACCINES WE CARRY</li>
<li>OTHER MEDICAL CENTRES</li>
<li>TYPES OF RESTRICTION OF ACQUIRING VACCINE</li>
</ul>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<script src="main-ajax.js"></script>
<!--Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
</body>
</html>
JSON & HTML data in JavaScript file
const openingInfo = {
"Monday": "9-5",
"Tuesday": "9-5",
"Wednesday": "9-5",
"Thursday": "9-5",
"Friday": "11-5",
"Saturday": "CLOSED",
"Sunday": "CLOSED"
}
const openingInfo = [
{
"day": "Monday",
"hours": "9-5"
},
{
"day": "Tuesday",
"hours": "9-5"
},
{
"day": "Wednesday",
"hours": "9-5"
},
{
"day": "Thursday",
"hours": "9-5"
},
{
"day": "Friday",
"hours": "11-4"
},
{
"day": "Saturday",
"hours": "CLOSED"
},
{
"day": "Sunday",
"hours": "CLOSED"
}
]
const vaccineTypes = "<ol><li>Moderna - 18 years older</li><li>Pfizer-BioNTech - 16 years older</li><li>AstraZeneca - 18 years older</li><li>Janssen - 18 years older</li></ol>";
const restrictInfo = "<ul><li>Individuals who have travelled outside of Canada less than two weeks prior.</li><li>Been in contacted with person(s) with COVID-19.</li><li>Have been infected with COVID-19 less than 2 months prior.</li><li>Any signs of symptoms (cough, fever, diahrrea)</li><li>Participated in any gathering of more than 10 people.</li></ul>";
JavaScript file to retrieve JSON & HTML file by using AJAX, GET and Node JS.
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const { JSDOM } = require('jsdom');
const fs = require("fs");
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use('/js', express.static('files'))
app.use('/css', express.static('files'))
app.get("/", (req, res) => {
const html = fs.readFileSync('./files/main.html', "utf8");
res.send(html);
});
app.get("/retrieve-AJAX-info", (req, res) => {
const formatOfResponse = req.query['format'];
const dataList = null;
if(formatOfResponse == 'opening-hour') {
res.setHeader('Content-Type', 'text/html');
dataList = lists.opening-hour();
res.send(dataList);
} else if(formatOfResponse == 'vaccine-types') {
res.setHeader('Content-Type', 'application/json');
dataList = lists.vaccine-types();
res.send(dataList);
} else if(formatOfResponse == 'location') {
res.setHeader('Content-Type', 'application/json');
dataList = lists.location();
res.send(dataList);
} else if(formatOfResponse == 'not-permitted') {
res.setHeader('Content-Type', 'application/json');
dataList = lists.not-permitted();
res.send(dataList);
} else {
res.send({msg: 'Wrong format!'});
}
});
app.use(function (req, res, next) {
res.status(404).send("<html><head><title>Page not found!</title></head><body><p>Nothing here.</p></body></html>");
})
// RUN SERVER
let port = 8000;
app.listen(port, function () {
console.log('You are listening to port ' + port + '.');
})

The variable dataList is defined as a const and should be let or var. Also the list variable isn't defined anywhere.
Perhaps inspecting the web browser console will show any other errors in the code.

Related

using ext.js in html file

I am new to ext.js and I need some explaination.
I wanto to use the ext.js features in a base html, without any use of html tags
I put the ext.js script tags in the html and I created an Application.js file which I reference in the html itself and which contains a simple Ext.application (....) (taken from a sencha blog).
My question is, can I simply use ext.js by inserting the script libraries references in the html, or should I do something else beforehand ?
I saw the sencha cmd on the sencha site, but i suspect its just used to create the structre of the application itself , putting the right files in the right places.
Since I can't visualize anything (apart from a js "alert" which I put at the beginning to seeif i call the right file), what am I doing wrong ?
This is my html :
#{
ViewData["Title"] = "Home Page";
}
<link href='~/ExtJS/Content/Css/prova.css' rel='stylesheet' />
<link rel="stylesheet" href="~/ExtJs/Content/Css/ext-all.css" />
<link rel="stylesheet" href="~/ExtJs/Content/Css/ext-all-debug.css" />
<script src="~/ExtJS/Scripts/ext-all-dev.js"></script>
<script src="~/ExtJS/Scripts/ext-all.js"></script>
<script src="~/ExtJS/Scripts/ext-lang-it.js"></script>
<script src="~/ExtJS/Src/Application.js"></script>
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about building Web apps with ASP.NET Core.</p>
</div>
This is my MVC layout file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - ExtJSApplication1</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
#*<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">ExtJSApplication1</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>*#
</header>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2021 - ExtJSApplication1 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
</body>
</html>
and this is my Application.js file :
alert('launch');
Ext.application({
launch: function () {
Ext.Viewport.add({
xtype: 'grid',
title: 'Users',
columns: [
{ text: 'Name', width: 100, dataIndex: 'name' },
{ text: 'Email Address', flex: 1, dataIndex: 'email' },
{ text: 'Phone Number', width: 200, dataIndex: 'phone' }
],
data: data,
listeners: {
select: onSelect
},
});
}
}
);
function onSelect(sender, record) {
var r = record[0].data;
var text = r.name + ' - ' + r.email + ' - ' + r.phone;
Ext.Msg.alert('Row Clicked', text);
};
var data = [
{ name: 'Lisa', email: 'lisa#simpsons.com', phone: '555-111-1224' },
{ name: 'Bart', email: 'bart#simpsons.com', phone: '555-222-1234' },
{ name: 'Homer', email: 'homer#simpsons.com', phone: '555-222-1244' },
{ name: 'Marge', email: 'marge#simpsons.com', phone: '555-222-1254' }
]
If you are planning to add ExtJS as a library instead of using it as a framework, you should do a build of the ExtJS abb beforehand and include the build files into your html.
Framework Approach
Install Sencha CMD
Start Windows PowerShell (or command line on your system)
follow this documentation to generate a workspace and an app
Run sencha app build production
Use the index.html from the build
If you need additional sources you can add them into the app.json file, that way all is loaded into the html file using ExtJS.
Library Approach
same as above, but instead of using the ExtJS html...
copy the js file and the css files into your own html (folder)
how I did was:
use ExtJS gpl cdn. OR down load and store it locally
in extjs use renderTo: your_div_id ,// to render ext component on particular div
note: I have extjs license.

XMLRequest not working to retrieve data and fill up data table

So what I'm trying to do is get data from a stored procedure and put it into a table on my website. When I call the API functions from my JS file (using XML REQUEST), the if statement never runs, and I never get a result back. Im not too sure where my error is because I don't get any error message, I just get no data returned into my table.
Function that calls to API from JS file
function getStudentTopicQuizResult()
{
console.log("step 1");
var req = new XMLHttpRequest();
req.open('POST', 'https://localhost:44303/api/JSON/getStudentTopicQuizResult', true);
req.setRequestHeader('Content-Type', 'application/json');
req.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200)
{
var result = req.response;
console.log("step 2");
}
}
return false;
}
ASP.NET API Functions
[System.Web.Http.HttpPost]
public object getStudentTopicQuizResult()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
string sql = "getStudentTopicQuizResult";
var json = ExecuteSPGetStudentTopicQuizResult(sql);
response.Content = new StringContent(json);
return response;
}
private static string ExecuteSPGetStudentTopicQuizResult(string queryString)
{
string json = "";
string connectionString = ConfigurationManager.AppSettings["dbconn"].ToString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand(queryString, conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// iterate through results, printing each to console
while (rdr.Read())
{
json += "{\"name\":\"" + (string)rdr[0].ToString() + " " + (string)rdr[1].ToString() + "\",\"";
json += "\"topic\":\"" + (string)rdr[2].ToString() + "\",\"";
json += "\"score\":\"" + (string)rdr[5].ToString() + "\",\"";
json += "\"ids\":\"" + (string)rdr[3].ToString() + "|" + (string)rdr[4].ToString() + "\"\"},";
Console.WriteLine(json);
}
}
return json;
}
}
SQL stored procedure code
USE [Capstone]
GO
/****** Object: StoredProcedure [dbo].[getStudentTopicQuizResult] Script Date: 3/29/2021 6:01:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[getStudentTopicQuizResult]
AS
BEGIN
select FirstName, LastName, QuizName, [StudentQuizScore].StudentID, [StudentQuizScore].QuizID, QuizScore
from [dbo].[StudentQuizScore]
inner join Student
on Student.StudentID = [StudentQuizScore].StudentID
inner join Quiz
on quiz.QuizID = [StudentQuizScore].QuizID
END
HTML code for website page with table (Script code at bottom)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">
<link rel="icon" type="image/png" href="../assets/img/favicon.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title id=tabtitle>
Teacher Home
</title> <!-- dependent on student login -->
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />
<!-- Fonts and icons -->
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,200" rel="stylesheet" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<!-- CSS Files -->
<link href="../assets/css/bootstrap.min.css" rel="stylesheet" />
<link href="../assets/css/now-ui-kit.css?v=1.3.0" rel="stylesheet" />
<!-- CSS Just for demo purpose, don't include it in your project -->
<link href="../assets/demo/demo.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">
</head>
<body class="profile-page sidebar-collapse">
<!-- Navbar -->
<nav class="navbar navbar-expand-lg bg-primary fixed-top navbar-transparent " color-on-scroll="400">
<div class="container">
<div class="collapse navbar-collapse justify-content-end" id="navigation" data-nav-image="../assets/img/blurred-image-1.jpg">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="welcome-page.html">Welcome/Overview</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar -->
<div class="page-header clear-filter page-header-small" >
<div class="page-header-image" data-parallax="true" style="background-image:url('../assets/img/capstone/space-bg.jpg');">
</div>
<div class="container">
<h1 id="pagetitle" class="title">Class's Future <!-- dependent on student login --></h1>
</div>
</div>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</div>
<div class="col-xl-10 ml-auto mr-auto text-center">
<table class="display" id="example">
<thead>
<tr>
<th>Student Name</th>
<th>Topic</th>
<th>Score</th>
<th>Quiz Response</th>
</tr>
</thead>
</table>
</div>
<footer class="footer">
<div class=" container ">
<nav>
<ul>
<li>
<a href="https://mhs.monroeps.org/" target="_blank">
Masuk High School
</a>
</li>
<li>
<a href="https://classroom.google.com/h" target="_blank">
Google Classroom
</a>
</li>
</ul>
</nav>
<div class="copyright" id="copyright">
©
<script>
document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))
</script> Designed and coded by Mike Aiello</a>
</div>
</div>
</footer>
<!-- Core JS Files -->
<script src="../assets/js/core/jquery.min.js" type="text/javascript"></script>
<script src="../assets/js/core/popper.min.js" type="text/javascript"></script>
<script src="../assets/js/core/bootstrap.min.js" type="text/javascript"></script>
<!-- Plugin for Switches, full documentation here: http://www.jque.re/plugins/version3/bootstrap.switch/ -->
<script src="../assets/js/plugins/bootstrap-switch.js"></script>
<!-- Plugin for the Sliders, full documentation here: http://refreshless.com/nouislider/ -->
<script src="../assets/js/plugins/nouislider.min.js" type="text/javascript"></script>
<!-- Plugin for the DatePicker, full documentation here: https://github.com/uxsolutions/bootstrap-datepicker -->
<script src="../assets/js/plugins/bootstrap-datepicker.js" type="text/javascript"></script>
<!-- Google Maps Plugin -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE"></script>
<!-- Control Center for Now Ui Kit: parallax effects, scripts for the example pages etc -->
<script src="../assets/js/now-ui-kit.js?v=1.3.0" type="text/javascript"></script>
<script src="../assets/js/core/helperFunctions.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>
</body>
<script>
$(document).ready(function(){
//var userName = getCookie('myFutureUserName');
var userName = localStorage.getItem('myFutureUserName');
var userID = localStorage.getItem('myFutureUserID');
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('dataKey');
var responseObj = getStudentTopicQuizResult();
/*var responseObj = [
{ "name":"A1", "topic": "A1", "score": "100", "ids": "1009|10" },
{ "name":"A2", "topic": "A1", "score": "100", "ids": "1009|1" }
];
*/
$('#example').dataTable({
"data": responseObj,
"columns": [
{ "data": "name" },
{ "data": "topic" },
{ "data": "score" },
{
"data": "ids",
"render": function(data, type, row, meta){
//if(type === 'display'){
data = '<button type="button" class="btn btn-info btn-sm" onclick="openModal(\'' + data + '\')" >Show Quiz Response</button>';
//}
return data;
}
}
]
});
});
function openModal(quizID) {
alert(quizID);
localStorage.setItem('quizResponseID', quizID);
$("#myModal").modal();
}
</script>
</html>

Bootstrap 3 disabled menu item (li) still goes to reference when clicked

I am using bootstrap 3 and I have a menu item that is disabled; however, when I select it I am still taken to the reference:
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="E1ActivitySelect.html">Activity - E1 Administration</a></li>
<li>Activity - E1</li>
<li class="divider"></li>
<li class="disabled">Camps</li>
<li><a class="dropdown-item" href="#">Hikes</a></li>
<li>Major Events</li>
<li>Pen Pals</li>
</ul>
How do I stop being taken to the reference (i.e., truly disable).
My js:
$(document).ready(function(){
$("#includedContent").load("Menu.html");
$(".dropdown-menu li.disabled a").click(function() {
return false;
});
$('[data-toggle="tooltip"]').tooltip();
selectPerson();
}); // end document.ready
Bootstrap doesn't really disable the inner anchor it just looks disabled. The correct way to do this is to define the anchor with no href thus:
<li class="disabled"><a>Camps</a></li>
If you need to have the href there, you will have to disable the click via JavaScript or jQuery:
$(document).ready(function() {
// For dynamically added elements
$(document).on("click", ".dropdown-menu li.disabled a", function() {
return false;
});
// For staticly loaded elemetns
/*
$(".dropdown-menu li.disabled a").click(function() {
return false;
});
*/
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="E1ActivitySelect.html">Activity - E1 Administration</a></li>
<li>Activity - E1</li>
<li class="divider"></li>
<li class="disabled">Camps</li>
<li><a class="dropdown-item" href="#">Hikes</a></li>
<li>Major Events</li>
<li>Pen Pals</li>
</ul>
</div>
If you are planning to add elements dynamically, you can attach the click handler to the document itself. The reason is because the event handlers in the jQuery code, are being attached the first time the page loads, when you add elements after page load, the code that attaches the event handling has run already so you either reattach the event handling to the newly inserted elements or just add it to the container element for these freshly loaded elements. document pretty much contains everyone so it's always a safe bet.
to fully stop/disabled a link you can use href="javascript:void(0) , this will stop your href to your anchor tag
​You can use just one CSS line to avoid events on any link:
pointer-events: none;​

Login button in my app not working. Server Responds with 404 on controllers

I am making a test app and User registration is going all fine but my Login button won't login because the server responds with 404 on controllers that have the logging in function.
The code for server.js is below:
var mongoose = require('mongoose');
var bodyParser = require ('body-parser');
var express = require('express');
var multiPart = require('connect-multiparty');
var multipartMiddleware = multiPart();
var app =express();
var authenticationController = require('./server/controllers/authenticationController');
var profileController = require('./server/controllers/profileController');
mongoose.connect('mongodb://localhost:27017/timeWaste');
app.use(bodyParser.json());
app.use(multipartMiddleware);
app.use('/app',express.static(__dirname + "/app"));
app.use('/node_modules', express.static(__dirname+"/node_modules"));
//Authentication
app.post ('/users/signup', authenticationController.signup);
app.post('/users/login', authenticationController.login);
//Profile
app.post('/profile/edit', multipartMiddleware, profileController.updatePhoto);
app.post('/profile/updateUsername', profileController.updateUsername);
app.post('/profile/updateBio', profileController.updateBio);
app.get('/', function(req,res) {
res.sendfile('index.html');
});
app.listen(3000, function() {
console.log('Listening');
});
The code for my navigationController where the login function is written is as follows:
(function(){
angular.module('TimeSuck')
.controller('navigationController',["$scope","$state","$http", function($scope, $state, $http){
if(localStorage['UserData']) {
$scope.loggedIn = true;
}
else {
$scope.loggedIn = false;
}
$scope.logUserIn = function() {
$http({
method: 'POST',
url:'users/login',
}).success(function(response){
localStorage.setItem('UserData', JSON.stringify(response));
}).error(function(error){
console.log(error);
})
}
}])
})();
and the code for my html is as follows:
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="shortcut icon" href="">
<script src="node_modules/angular/angular.js"> </script>
<script src="app/app.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.js"> </script>
<script src="/app/signup/SignUpController.js"> </script>
<script src="/app/profile/edit-profile-controller.js"> </script>
<script src="/server/controllers/navigationController.js"></script>
<script src="/server/controllers/profileController.js"></script>
</head>
<body ng-app="TimeSuck" ng-controller="SignUpController">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/index.html"> Deav's Blog </a>
</div>
<ul class="nav navbar-nav">
<li> <div ng-show="!loggedIn">
Email: <input type="text" ng-model="login.email"> Password: <input type="password" ng-model="login.password">
<button type="submit" ng-click="logUserIn()"> login </button> <a ui- sref="signUp"> Create an Account </a> </li>
</ul>
<div ng-show="loggedIn"> <a ui-sref="editProfile"> </a> </div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h1> The Smartphones </h1>
<p> This page features all the smartphones you'd want to buy and use </p>
</div>
</div>
<div ui-view> </div>
</body>
<!-- Libraries -->
<script src="node_modules/ng-file-upload/dist/ng-file-upload-all.js"></script>
<script src="node_modules/ng-file-upload/dist/ng-file-upload-shim.js"></script>
<script src="node_modules/ng-file-upload/dist/ng-file-upload.js"> </script>
Screenshot of the error:
Screenshot of the error
Why 404 error in console
In your node server ,
you defined like this one.
app.use('/app',express.static(__dirname + "/app"));
// its fine if app folder is within your root folder.
means your static resources come under app folder.
Here you,saying that your JS file come under app folder.
check second parameter.(__dirname + "/app").
So,whatever you include is script,it should contain path starts from app.
e.g.
<script src="/server/controllers/navigationController.js"></script> //its wrong
it should be
<script src="app/server/controllers/navigationController.js"></script>
In your service.js your controller paths are as follows :
'./server/controllers/profileController', './server/controllers/authenticationController'
But in your html, the paths are
<script src="/server/controllers/navigationController.js"></script>
<script src="/server/controllers/profileController.js"></script>
Are they pointing to proper paths? Pls make sure the paths are proper.

Angular routing setup 404 error, probably operator error

I have the following code which is giving me the old
Failed to load resource: the server responded with a status of 404 (Not Found)
error and I'm not seeing my views. The main.js file is on the same level in the project as index.html.
I built it in Webstorm 10 and I've been staring and rearranging stuff for two days now. I'm starting to get cross-eyed looking at it. If anyone can point out what I'm missing or if I wrote something wrong, it'd be a big help.
EDIT :
I edited the html because this was missing the ng-view element. I'm using the localhost server built into Webstorm to debug. The first template that should be seen upon the project being loaded, about.html, was the file that couldn't be loaded from the project. For that matter though, I get an error trying to load each of the templates.
EDIT 2:
I'm getting the idea it has something to do with Webstorm. If I start a default Angular project and fire it up in a browser, I get a whole bunch of failure to load resource errors.
index.html
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="node_modules/angular/angular.js"></script>
<script type="text/javascript" src="node_modules/angular-route/angular-route.js"></script>
<script type="text/javascript" src="main.js"></script>
<link href="node_modules/bootstrap/dist/css/bootstrap.css" rel="stylesheet"/>
<link href="content/css/custom.css" rel="stylesheet"/>
<base href="/" />
</head>
<body>
<nav class="navbar navbar-fixed-top cstmNavbar">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar-collapse"
aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Brand</a>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav">
<li>Voice Over</li>
<li>Conventions</li>
<li>Contact</li>
<li>Other Links</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
main.js
var app = angular.module("app", ['ngRoute']);
app.config(function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
templateUrl: '/views/about.html',
controller: 'aboutCtrl'
})
.when('/voiceover', {
templateUrl: '/views/voiceover.html',
controller: 'voiceoverCtrl'
})
.when('/conventions', {
templateUrl: '/views/conventions.html',
controller: 'conventionsCtrl'
})
.when('/contact', {
templateUrl: '/views/contact.html',
controller: 'contactCtrl'
})
.when('/other', {
templateUrl: '/views/other.html',
controller: 'otherCtrl'
})
.otherwise({
redirectTo: '/'
});
});
app.controller("mainCtrl", function ($scope) {
});
app.controller("aboutCtrl", function ($scope) {
});
app.controller("voiceoverCtrl", function ($scope) {
});
app.controller("conventionsCtrl", function ($scope) {
});
app.controller("contactCtrl", function ($scope) {
});
app.controller("otherCtrl", function ($scope) {
});
Add in yor html code
<ui-view></ui-view>
This tag load html view