When I call a get request, I am getting the ngRepeat:Dupes error because what my get request is getting me from a console.log shows me the hard-coded html code from the page itself.
Here is the console.log
mainController.js:10 <!DOCTYPE>
<html ng-app="myApp">
<head>
<title>Social Network Tutorial</title>
<link rel="stylesheet" href="libs/bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="libs/bootstrap/css/bootstrap-theme.min.css"/>
<link rel="stylesheet" href="css/stylesheet.css"/>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top" ng-controller="navigationController">
<div class="container">
<div ng-show="!loggedIn">
<input type="text" ng-model="login.email">
<input type="password" ng-model="login.password">
<button ng-click="logUserIn()">Login</button>
<a ui-sref="signUp">Create An Account</a>
</div>
<div ng-show="loggedIn">
<a ui-sref="editProfile">Edit Profile</a>
<a ng-click="logOut()">Logout</a>
</div>
</div>
</nav>
<div ui-view></div>
<!--Libraries-->
<script type="text/javascript" src="libs/angular/angular.min.js"></script>
<script type="text/javascript" src="libs/angular-ui-router/angular-ui-router.min.js"></script>
<script type="text/javascript" src="libs/ng-file-upload/ng-file-upload.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<!--Controllers-->
<script type="text/javascript" src="partials/signup/signupController.js"></script>
<script type="text/javascript" src="partials/navigation/navigationController.js"></script>
<script type="text/javascript" src="partials/profile/editProfileController.js"></script>
<script type="text/javascript" src="partials/main/mainController.js"></script>
</body>
</html>
My client side controller shows the following code:
var getTweets = function(initial){
$http.get('/tweets').then(function(response){
if(initial){
$scope.tweets = response.data;
} else {
$scope.incomingTweets = response.data;
};
});
};
getTweets(true);
and my server side api function is the following:
router.get('/tweets', tweetController.getTweets);
lastly the server side controller is the following:
module.exports.getTweets = function(req,res){
console.log("works");
Tweet.find({}).sort({date: -1}).exec(function(err, data){
if(err) {
throw err;
res.json({status: 500});
} else {
console.log(data);
res.json(data);
};
});
};
What did I do wrong?
The console.log on the server side doesn't show "works" meaning the request didn't even reach the server but for some reason the client side got a response.
The server probably returned an error page. Inspect the html that was returned to see what's going on, it probably contains some information.
Debug your app by executing the url /tweets in the browser or Postman (or use Chrome dev tools). If the server doesn't return json, either the url is wrong or something is wrong server side. That eliminates a bug in the client side.
Related
I have seen many questions similar to this one on here but none of them seem to fix the problem I am having.
I keep getting the following error-
Uncaught SyntaxError: Unexpected token <
It says the error is in line one of the js file but the sources only shows a red line on line one of the html file.
Should also mention it is running on a go server.
Thanks a mil!
Here is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Sourcing jquery and ajax -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--external script.js file-->
<script type = "text/JavaScript" src="ChatBot.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<style>
body {
padding-top: 65px;
padding-bottom: 100px;
}
</style>
</head>
<body>
<nav class="navbar fixed-top navbar-dark bg-dark">
<a class="navbar-brand" href="#">Eliza chat bot</a>
</nav>
<div class="container-fluid">
<ul class="list-group">
<div class="fixed-bottom bg-dark p-2">
<div class="container">
<div>
<ul class="list-group"></ul>
</div>
<form action="/Chat" method="GET">
<div class="form-group">
<input type="text" class="form-control" id="userInput" placeholder="Talk to eliza...">
</div>
</form>
</div>
</div>
</ul> </div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
and here is my js
const form = $("#userInput");
const listItem = $("#list-group");
//add the keypress function for when the user types an input for eliza to compute
$(document).ready(()=>{
form.keypress(function(event){
const keyCodes = {
ENTER : 13
}
let keyCode = event.keyCode;
//for enter
if(event.keyCode != keyCodes.ENTER){
return;
}
event.preventDefault();
const input = form.val();
form.val(" ");
listItem.append("<li class='list-group-item list-group-item-success'>"+"User : " + input + "</li>");
// GET/POST
const queryParams = {"userInput" : input }
$.get("/Chat", queryParams)
.done(function(response){
var nextListItem = "<li class='list-group-item list-group-item-info'>"+"ELiza : " + response + "</li>";
setTimeout(function(){
listItem.append(nextListItem)
}, 1000);//set timeout to give wait to response
}).fail(function(){
var nextListItem = "<li class='list-group-item list-group-item-danger' >Sorry I'm not home right now.</li>";
list.append(nextListItem);
});
});
});
Does your webserver happen to have a rule where if the requested resources is not found it will default to serving the index.html file? This is a popular configuration for Single Page Applications.
If that is the case, if the server can not find the js file requested it will serve the contents of the html file, which the browser will try parse as JavaScript. Since the first character on the first line of the html file is < you'll get a syntax error since that is not valid JavaScript.
I am following a tutorial in Jasmine and serverless. The problem I am facing is around Javascript.
There is a public directory which has an index.html
Jasmine tests are in public/tests directory. It also has an index.html.
Following JS code (SpecHelper.js below) is suppose to find markups with class markup in public/index.html and copy that code in <body> of public/tests/index.html but it isn't doing so. I am unable to find the issue.
public/index.html
<body>
<div class='markup'>
<div class='view-container container'>
<div class='one-half column'>
<h3>Learn JS, one puzzle at a time</h3>
<a href='' class='button button-primary'>Start now!</a>
</div>
<div class='one-half column'>
<img src='/images/HeroImage.jpg'/>
</div>
</div>
</div>
</body>
SpecHelper.js
var fixture;
function loadFixture(path) {
var html;
jQuery.ajax({
url: '/index.html',
success: function(result) {
html = result;
},
async: false
});
return $.parseHTML(html);
}
function resetFixture() {
if (!fixture) {
var index = $('<div>').append(loadFixture('/index.html'));
var markup = index.find('div.markup');
fixture = $('<div class="fixture" style="display: none">').append(markup);
$('body').append(fixture.clone());
} else {
$('.fixture').replaceWith(fixture.clone());
}
}
beforeEach(function () {
resetFixture();
});
public/tests/index.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jasmine Spec Runner v2.3.4</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.3.4/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.3.4/jasmine.css">
<!-- App Dependencies -->
<script src="lib/jquery-2.1.4.js"></script>
<script src="/vendor.js"></script>
<!-- Test libraries -->
<script type="text/javascript" src="lib/jasmine-2.3.4/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-2.3.4/jasmine-html.js"></script>
<script type="text/javascript" src="lib/jasmine-2.3.4/boot.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="/app.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="SpecHelper.js"></script>
<script type="text/javascript" src="app_spec.js"></script>
</head>
<body>
<!--This is always empty! -->
</body>
</html>
The test in Jasmine fails with following error
1 spec, 1 failure
Spec List | Failures
learnJS can show problem view
Expected 0 to equal 1.
Try this
fixture = $('<div class="fixture" style="display: none">').append(markup.html());
Then maybe
$('body').append(fixture.clone().html());
got it working..phew ... had to clear browser cache by going to developer tools, networks. I noticed that most files were being picked from memory. Right clicked and cleared cache and cookies.
I'm building an app with an Express/Node backend and Angular JS for the front end. Kinda new to using this stack and I'm having a hard time receiving the data in an Angular Service + Controller
Backend: Users can authenticate with Facebook using Passport JS that attaches a users object to every request. I opened up an endpoint that checks if req.user exists, like so:
app.get('/checklogin', function(req,res,next){
if(req.user){
console.log("we found a user!!!");
console.log("name:" + req.user.displayName);
console.log("user id" + req.user.id);
return res.status(201).json(req.user);
} else {
console.log("there is no user logged in");
}
});
If the req.user exists, so the user is authenticated, it sends a JSON response.
What I'm trying to do is in Angular is sending a http.get to this /checklogin endpoint and handle the response. I want to bind to the scope if the user is authenticated (req.user exists or not), and if so bind displayName and Id as well, and hide show nav links and pages.
But my setup in Angular hits the API endpoint but doesnt seem to receive any data????:
.service("Login", function($http){
this.isLoggedIn = function(){
return $http.get("/checklogin")
.then(function(response){
console.log(response)
return response;
}, function(response){
console.log("failed to check login");
});
};
})
.controller("mainController", function($scope, Login){
Login.isLoggedIn()
.then(function(doc){
console.log(doc);
console.log(doc.data);
}, function(response){
alert(response);
});
})
the console.log(doc) and console.log(doc.data) don't log anything...... What am I doing wrong here?????
More info: the mainController is loaded in the index.html file:
<html lang="en" ng-app="myApp" ng-controller="mainController">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--load jQuery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!--load Bootstrap JS-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!--load Angular JS-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.js"></script>
<!--latest compiled and minified Bootstap CSS-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--link custom CSS file-->
<link rel="stylesheet" type="text/css" href="/css/style.css">
<script src="/js/app.js"></script>
</head>
<body>
<!-- NAVBAR ================== ---->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<div class="nav-header">
<a class="navbar-brand" href="#/">Votely</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li class="active">Home</li>
<li>Sign in with Facebook</li>
<li>Sign Out</li>
</ul>
</div>
</div>
</nav>
<!-- Dynamically render templates Angular JS -->
<div class="container" ng-view>
</div>
</body>
Any help much appreciated, thanks!
You should return a promise from service if you are using then inside controller i.e.
.service("Login", function($http){
this.isLoggedIn = function(){
return $http.get("/checklogin");
};
.isLoggedIn function in your service should looks like this:
this.isLoggedIn = function(){
return $http.get("/checklogin");
}
thanks, I got it working now. I was using the browser in Cloud 9 IDE and the server was sending a 503 response, not sure why. It works now in Chrome and Firefox etc. after I set the service to return a promise!
I am brand new to marionette and am following along with a textbook to build a simple app using marionette. I ran into this problem almost immediately, they telly you to put a console.log() in a function, except it doesn't show up in my browser when i run it. Here's the script below:
<script type="text/javascript">
var ContactManager = new Marionette.Application();
ContactManager.on("initialize:after", function(){
console.log("ContactManager has started!");
});
ContactManager.start();
</script>
And here's the whole HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Marionette Contact Manager</title>
<link href="./assets/css/bootstrap.css" rel="stylesheet">
<link href="./assets/css/application.css" rel="stylesheet">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<span class="brand">Contact manager</span>
</div>
</div>
</div>
<div class="container">
<p>Here is static content in the web page. You'll notice that it gets 21 replaced by our app as soon as we start it.</p>
</div>
<script src="./assets/js/vendor/jquery.js"></script>
<script src="./assets/js/vendor/json2.js"></script>
<script src="./assets/js/vendor/underscore.js"></script>
<script src="./assets/js/vendor/backbone.js"></script>
<script src="./assets/js/vendor/backbone.marionette.js"></script>
<script type="text/javascript">
var ContactManager = new Marionette.Application();
ContactManager.on("initialize:after", function(){
console.log("ContactManager has started!");
});
ContactManager.start();
</script>
</body>
</html>
Any help would be greatly appreciated, I can do a console.log() outside of the ContactManager.on() code and it will work. Any ideas?
So i figured out the answer to my own question with a little research. Marionette has updated "initialize:after" to "start". For a full list of updates you can check here -->
https://github.com/marionettejs/backbone.marionette/blob/master/changelog.md#v100-rc1-view-commit-logs
I'm building a sample application with YouTube API (v3), that would provide a list of videos based on a search term. The concept is to populate the page using the data from the response.
I have used the client library documented in v3 to access the API, and send my request, however I don't know how to properly navigate through the data provided in the response in order to display the desired elements. The code below shows my script, where I am trying to access and list the title of the videos in the response:
$(function () {
//FUNCTION TO COLLECT QUERY TERM FROM SEARCH FORM
var $searchField = $('#search-text');
$('#mainSearch'). on ('submit', function(e){
e.preventDefault();
if ($searchField.val() !== '') { //IF SEARCH FORM IS NOT EMPTY
var $searchQuery = $searchField.val()+ ' parody'; //PREPARE SEARCH QUERY
makeRequest($searchQuery); //PASS SEARCH QUERY TO REQUEST FUNCTION
}
else {
$searchField.focus(); //ADD ERROR CLASS HERE
$searchField.blur(function (e){
//REMOVE ERROR CLASS HERE
});
}
});
function makeRequest(query){
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: query
});
$('.content').empty();
request.execute(parseResponse);
}
function parseResponse(data) {
$.each(data, function (i, items){
var $infoDiv = $('<div></div>');
$infoDiv.append('<p>'+ items.snippet.title +'</p>');
$('.content').append($infoDiv);
});
}
});
//LOAD API CLIENT
function initClient() {
gapi.client.load('youtube', 'v3');
gapi.client.setApiKey('AIzaSyARVmOp3tBIA3ZgW6z4DK_-1sMJwulPvps');
}
However my page does get not populated with any data, and I get this error in my console:
Uncaught TypeError: Cannot read property 'title' of undefined
And here is the markup for my page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Parrdy Template</title>
<!--
<Bootstrap></Bootstrap>-->
<link href="stylesheets/bootstrap.min.css" rel="stylesheet"/>
<link href="stylesheets/style.min.css" rel="stylesheet"/>
<!--
<HTML5>Shim and Respond.js IE8 support of HTML5 elements and media queries </HTML5>--><!--
<WARNING>
<Respond class="js">doesn't work if you view the page via file:// </Respond>
</WARNING>--><!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script><![endif]-->
</head>
<body>
<div class="container">
<div class="header">
<img src="/images/Logo1_mod.png" width="200">
<form role="form" id= "mainSearch" class="navbar-form navbar-right pull-right">
<div class="form-group">
<input type="text" id="search-text" placeholder="Search" class="form-control">
</div>
<button type="submit" id="vid-search" class="btn btn-sm btn-warning">Search</button>
</form>
</div>
{{{body}}}
<div class="footer">
<ul class="nav nav-pills pull-left">
<li><a class="customcolor" href="#">About</a></li>
<li><a class="customcolor" href="#">Contact Us</a></li>
</ul>
</div>
</div><!--container ends-->
<!--
<jQuery>(necessary for Bootstrap's JavaScript plugins) </jQuery>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><!--
<Include>all compiled plugins (below), or include individual files as needed</Include>-->
<script src="js/bootstrap.min.js"></script>
<script src="js/core1.1.js"></script>
<script src="https://apis.google.com/js/client.js?onload=initClient" type="text/javascript">
</script>
</body>
</html>
Any help on how to access the elements correctly from a YouTube API response would be appreciated. Thanks.
The first thing you'll want to keep in mind is that the stuff you are after is nested in the response as data so you need to access 'response.data' and within that data is an array of items. You'll want to access the first array with items[0] now you can grab the id from here or go deeper with .snippet or .statistic
get(url)
.then(response => {
id: response.DATA.items[0].id
title: response.DATA.items[0].snippet.title
}
.catch(
error => {console.log(error)}
You should change your loop like this:
$.each(data.videos, function (i, items){
var $infoDiv = $('<div></div>');
$infoDiv.append('<p>'+ items.snippet.title +'</p>');
$('.content').append($infoDiv);
});