Mean stack controller server side not connecting to API - javascript

I am new to Mean stack and have been struggling with this for quite a few days.
To give you an idea of what I am trying to make; I am creating a tagging tool that stores all requests and their tags in a collection called tags and then also storing all of the distinct tags into the Tagnames collection. I would like to understand why my MEAN stack api layer gives me a 404 error.
This error only occurs with my put method in the server.js file.
TaggingTool\server.js
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
tagsController = require('./server/controllers/tagscontroller');
mongoose.connect('mongodb://localhost:27017/STDBank');
app.use(bodyParser());
app.get('/', function (req, res) {
res.sendfile(__dirname + '/client/views/index.html');
});
app.use('/js', express.static(__dirname + '/client/js'));
//REST API
app.get('/api/tags', tagsController.list);
app.get('/api/tagnames', tagsController.listName);
app.post('/api/tags', tagsController.create);
app.put('/api/tagUpdate/:id', tagsController.update);
app.listen(3000, function() {
console.log('I\'m Listening...');
})
TaggingTool\server\models\tag.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TagSchema = new Schema({
request: String,
intentTag: String
}, {collection : "requests"});
module.exports = mongoose.model('Tag', TagSchema);
TaggingTool\server\models\name.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var nameSchema = new Schema({
name: String
}, {collection : "tags"});
module.exports = mongoose.model('TagName', nameSchema);
TaggingTool\server\controllers\tagscontroller.js
var Tag = require('../models/tag');
var TagName = require('../models/name');
module.exports.create = function (req, res) {
var tag = new Tag(req.body);
tag.save(function (err, result) {
res.json(result);
});
}
module.exports.listName = function(req, res){
TagName.find({}, function(err, results){
res.json(results);
});
}
module.exports.list = function (req, res) {
Tag.find({}, function (err, results) {
/*var arr = [];
for(var i = 0; i<results.length;i++){
if(results[i].intentTag){
console.log("enter if: ", results[i].intentTag);
}//end of if statement
else{
console.log("enter if: ", results[i].intentTag);
console.log("enters else statement ", arr);
arr.push({
_id : results[i]._id,
request : results[i].request
});
}//end of else statement
}//end of for loop
console.log("results ",arr);
*/
res.json(results);
});
}
module.exports.update = function(req, res){
console.log("Server side entered", res);
Tag.findByIdAndUpdate(req.params.id, {
$set: {
request: req.body.request,
intentTag: req.body.intentTag
}
}, function (err, tag){
if(err) res.send(err);
res.json(tag);
});
}
TaggingTool\client\js\controllers\tagsController.js
app.controller('tagsController', ['$scope', '$resource', function ($scope, $resource) {
var Tag = $resource('/api/tags');
var TagName = $resource('/api/tagnames');
var tagUpdate = $resource('/api/tagUpdate/:id');
Tag.query(function (results) {
$scope.tags = results;
});
TagName.query(function(results){
$scope.tagnames = results;
});
tagUpdate.query(function(results){
$scope.tags = results;
console.log("results: ", results);
});
//$scope.tags = [];
$scope.newtags=[];
console.log("tagReq", $scope);
$scope.newTag = function (index) {
console.log("newTag initiated");
var ntag = new tagUpdate();
console.log("_id: ", index);
var k = $scope.tagReq.request;
console.log("request: ", k);
var t = $scope.newTagName.tagname.name;
console.log("intentTag: ", t);
ntag._id = index;
ntag.request = $scope.tagReq.request;
ntag.intentTag = $scope.newTagName.tagname.name;
console.log("Tags: ", index);
$scope.ntag.$update({_id: index}, ntag);
}
$scope.createTag = function () {
var tag = new Tag();
tag.request = $scope.tagReq;
tag.intentTag = $scope.tagName;
tag.$save(function (result) {
$scope.tags.push(result);
$scope.tagName = '';
});
}
}]);
TaggingTool\client\js\app.js
var app = angular.module('taggingApp', ['ngResource'])
TaggingTool\client\views\index.html
<!DOCTYPE html>
<html ng-app="taggingApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Tagging Tool </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<link rel="stylesheet" href="http://mbenford.github.io/ngTagsInput/css/ng-tags-input.min.css" />
<!-- Meetups View -->
<div ng-controller="tagsController">
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<caption><b><strong><em>Requests and their Tags</em></strong></b></caption>
<tr ng-repeat="tag in tags ">
<th ng-model="tagReq">{{tag.request}}</th>
<th>
<select ng-model="newTagName" ng-options="tagname.name for tagname in tagnames">
<option value="" >Select Tag</option>
</select>
<form ng-submit="newTag(tag._id)">
<input type="text" placeholder="Tag Name" ng-model="newTagName.tagname.name"></input>
<input type="submit"/>
</form>
<p>{{newTagName.tagname.name}}</p>
<p>{{tagReq.tag.request}}</p>
</th>
</tr>
</table>
<form ng-submit="createTag()">
<input type="text" placeholder="Tag name" ng-model="tagName"></input>
<button type="submit">Add</button>
</form>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-resource.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script>
<script src="http://mbenford.github.io/ngTagsInput/js/ng-tags-input.min.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
<script type="text/javascript" src="/js/controllers/tagsController.js"> </script>
</body>
</html>
I apologize for the terrible code and coding conventions, if anyone could help I would be extremely thankful.

I assume, this problem only occurs when you try to update from your Angular client? If so: Angular's $resource does not have an update method using PUT methods by default, see here.
You will need to define this manually, something along the lines:
$resource('/api/tagUpdate/:id', { id: '#_id' }, {
'update': { method: 'PUT' }
});
You can then use the resource's update method for performing your update.
Additional hint: With regards to REST conventions, I would not call the URL tagUpdate, but rather tags or something like this. The fact that you're updating is given by the HTTP method PUT already.

Related

Getting node.js output(from Mysql) to Javascript(client-side)

Title says it all I have a freelance project( first one and I promised it would be done by now) and I still can't figure it out. I just want the Name column from my MySQL database (that is being shown on my node.js when I console.log the results) into a JavaScript file. ( I feel like this is a simple solution staring me in the face and I can't figure it out)
**CLIENT SIDE**
var results = ("server.js")
var nodes = new vis.DataSet([
{label: "Pop"},
{label: "Alternative"},
{label: "Rock"},
{label: "Jazz"},
{label: "Hits"},
{label: "Dance"},
{label: "Metal"},
{label: "Experimental"},
{label: "Rap"},
{label: "Electronic"},
]);
var edges = new vis.DataSet();
var container = document.getElementById('bubbles');
var data = {
nodes: nodes,
edges: edges
};
var options = {
nodes: {borderWidth:0,shape:"circle",color:{background:'#F92C55', highlight:{background:'#F92C55', border: '#F92C55'}},font:{color:'#fff'}},
physics: {
stabilization: false,
minVelocity: 0.01,
solver: "repulsion",
repulsion: {
nodeDistance: 40
}
}
};
var network = new vis.Network(container, data, options);
// Events
network.on("click", function(e) {
if (e.nodes.length) {
var node = nodes.get(e.nodes[0]);
// Do something
nodes.update(node);
}
});
container.on("mouse-wheel", function(event) {
// prevents zooming with the mouse-wheel event
event.stopPropagation();
});
console.log (results.name)
**SERVER SIDE**
var mysql = require('mysql');
var express = require('express');
const path = require('path')
// var index = require("index.html")
app = express();
app.get('/',(request,response)=>{
;
response.sendFile(path.join(__dirname, '/index.html'));
app.use(express.static((__dirname)));
});
//Binding the server to a port(3000)
app.listen(3000,()=>console.log("express server started at port 3000"));
var con = mysql.createConnection({
host: "localhost",
user: "Nate",
password: "Black1022!",
database: "new_schema"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("SELECT Name FROM test", function (err, result) {
if (err) throw err;
console.log(result);
module.exports = result;
});
});
#bubbles {
position: absolute;
width: 100vw;
height: 100vh;
top: 0;
left: 0;
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Apple Music Style Bubble UI</title>
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div id="bubbles"></div>
<!-- partial -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.min.js'></script>
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<script src="./script.js"></script>
</body>
</html>
I would just remake the whole thing using MVC architecture but I feel like that would take too much time and then I feel like I would be at a loss again anyways.
edit: The "label" part will be replace by the names in the database.
Thanks for the help in advance!!

"events.js: 377" occurs when I am running the app.js as a node server on Hyper cmd

"events.js: 377" occurs when I am running the app.js as a node server on Hyper. Please also mention the full descriptive meaning of this "events.js: 377" and how we can figure it out this.
I am coding a Signup Newsletter and the code related to .html, .js and .css files are attached below.
I have many times changed the pattern of my code but I am not able to run the app.js as it is getting crashed every time.
If anybody knows about the solution then please answer.
Given below is link of the image of the error that is shown on the hyper when I run app.js as a server and it gets crashed.
The below given code is of app.js :
const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/signup.html");
})
app.post("/", function(req, res){
const firstName = req.body.fName;
const lastName = req.body.lName;
const email = req.body.email;
const data = {
members:[
{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}
]
}
});
const jsonData = JSON.stringify("data");
const url = "https://us5.api.mailchimp.com/3.0/lists/21760b9a041";
const options = {
method: "POST",
auth: "xxxx"
}
const requestt = https.request(url, options, function(response) {
response.on("data", function(data){
console.log(JSON.parse(data));
})
requestt.write(jsonData);
requestt.end
});
app.listen("3000", function(){
console.log("Server is running on port 3000");
});
The given below code is of signup.html :
***<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.88.1">
<title>Signin Template · Bootstrap v5.1</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/sign-in/">
<!-- When Internet will be ON only then this link of Bootstrap will be applied to your website. -->
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-uWxY/CJNBR+1zjPWmfnSnVxwRheevXITnMqoEIeG1LJrdI0GlVs/9cVSyPYXdcSF" crossorigin="anonymous">
<!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.1/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.1/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.1/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.1/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.1/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.1/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#7952b3">
<!-- Custom styles for this template -->
<link href="css/styles.css" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="/" method="POST">
<img class="mb-4" src="Image/lab.jpg" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Signup to my Newsletter.</h1>
<input type="text" name = fName class="form-control middle" id="inputPassword" placeholder="First Name" required>
<input type="text" name = lName class="form-control top" id="inputEmail" placeholder="Last Name" required autofocus>
<input type="email"name = email class="form-control bottom" placeholder="Email" required>
<button class="w-100 btn btn-lg btn-primary btn-block" type="submit">Sign Me Up!</button>
<p class="mt-5 mb-3 text-muted">© 2017–2021</p>
</form>
</body>
</html>***
The given below code is of styles.css :
body {
height: 100%;
}
body {
display: flex;
align-items: center;
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: auto;
}
.form-signin .checkbox {
font-weight: 400;
}
.form-signin .form-floating:focus-within {
z-index: 2;
}
.top {
margin-bottom: 2px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.middle {
border-radius: 0;
margin-bottom: 2px;
}
.bottom{
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
Looks like you are very new to javascript. I would recommend formatting your code a bit better and you might catch errors like these a bit easier.
The exact cause of your error is that you are getting an error when making your API request to mailchimp and you do not have an error handler. Secondarily the reason you are likely getting that error is due to the fact that you are just sending them the literal string 'data' and nothing else.
Your code when properly formatted looks like this:
app.post("/", function(req, res) {
const firstName = req.body.fName;
const lastName = req.body.lName;
const email = req.body.email;
const data = {
members: [{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}]
}
});
const jsonData = JSON.stringify("data");
const url = "https://us5.api.mailchimp.com/3.0/lists/21760b9a041";
const options = {
method: "POST",
auth: "xxxx"
};
const requestt = https.request(url, options, function(response) {
response.on("data", function(data) {
console.log(JSON.parse(data));
});
requestt.write(jsonData);
requestt.end
});
Note that your post to mailchimp is outside of your app.post callback handler. Due to that code's location it will execute the moment you run your code. First you need to move this code inside your route handler.
app.post("/", function(req, res) {
const firstName = req.body.fName;
const lastName = req.body.lName;
const email = req.body.email;
const data = {
members: [{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}]
};
const jsonData = JSON.stringify("data");
const url = "https://us5.api.mailchimp.com/3.0/lists/21760b9a041";
const options = {
method: "POST",
auth: "xxxx"
};
const requestt = https.request(url, options, function(response) {
response.on("data", function(data) {
console.log(JSON.parse(data));
});
requestt.write(jsonData);
requestt.end
});
});
This will prevent your code from executing the moment you run your code.
Secondly you need to add an error handler to your request method so that if an error occurs you do not cause an unhandled error to crash your program. That is what is causing you to see the Unhandled 'error' event message right below events:377.
const requestt = https.request(url, options, function(response) {
response.on("data", function(data) {
console.log(JSON.parse(data));
});
response.on("error", function(error) {
console.error('Error from mailchimp', error);
});
requestt.write(jsonData);
requestt.end
});
Lastly, the actual error you are seeing is socket hang up. This error is generally a network error meaning that your client's TCP requests to the target server were dropped/rejected or otherwise terminated before they could be completed. This may be a result of not actually calling the end function when making your request. Specifically you have requestt.end, which is a function, but you are not calling it, should be requestt.end();. If this doesn't resolve it then you may want to check the network connectivity of the computer you are running this code on.
Another error I noticed in your code:
const jsonData = JSON.stringify("data");
You probably mean to send the data object that you are creating, in that case you do not want to wrap data in quotes as it is a variable name, not a string. Instead it should be:
const jsonData = JSON.stringify(data);
I also experienced the same issue and I got this fixed. The root cause at my end was that port number I used was engaged/used at another program.
app.listen("3000", function(){...
Once I closed the other program that was using this port number, my program worked fine.

<audio> tag not working with IBM Watson Text-to-Speech Node.js api

I'm building a chatbot using IBM Watson on Node.js and I'm having some trouble integrating the text-to-speech api. I've cloned an example on github that works when I run it, but when I try to implement it into my code, no audio plays.
app.js(server side):
/**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
require( 'dotenv' ).config( {silent: true} );
const TextToSpeechV1 = require('watson-developer-cloud/text-to-speech/v1');
var express = require( 'express' ); // app server
var bodyParser = require( 'body-parser' ); // parser for post requests
var Watson = require( 'watson-developer-cloud/conversation/v1' ); // watson sdk
// The following requires are needed for logging purposes
var uuid = require( 'uuid' );
var vcapServices = require( 'vcap_services' );
var basicAuth = require( 'basic-auth-connect' );
// The app owner may optionally configure a cloudand db to track user input.
// This cloudand db is not required, the app will operate without it.
// If logging is enabled the app must also enable basic auth to secure logging
// endpoints
var cloudantCredentials = vcapServices.getCredentials( 'cloudantNoSQLDB' );
var cloudantUrl = null;
if ( cloudantCredentials ) {
cloudantUrl = cloudantCredentials.url;
}
cloudantUrl = cloudantUrl || process.env.CLOUDANT_URL; // || '<cloudant_url>';
var logs = null;
var app = express();
// set up routes
var token = require('./routes/token');
app.use('/token', token);
// Bootstrap application settings
app.use( express.static( './public' ) ); // load UI from public folder
app.use( bodyParser.json() );
// Create the service wrapper
var conversation = new Watson( {
// If unspecified here, the CONVERSATION_USERNAME and CONVERSATION_PASSWORD env properties will be checked
// After that, the SDK will fall back to the bluemix-provided VCAP_SERVICES environment property
// username: '<username>',
// password: '<password>',
username: process.env.ASSISTANT_USERNAME || '<username>',
password: process.env.ASSISTANT_PASSWORD || '<password>',
url: 'https://gateway.watsonplatform.net/conversation/api',
version_date: '2016-09-20',
version: 'v1'
} );
const textToSpeech = new TextToSpeechV1({
username: process.env.TEXT_TO_SPEECH_USERNAME,
password: process.env.TEXT_TO_SPEECH_PASSWORD,
version: 'v1'
// If unspecified here, the TEXT_TO_SPEECH_USERNAME and
// TEXT_TO_SPEECH_PASSWORD env properties will be checked
// After that, the SDK will fall back to the bluemix-provided VCAP_SERVICES environment property
// username: '<username>',
// password: '<password>',
});
/************************************************
* Conversation services
************************************************/
// Endpoint to be call from the client side
app.post( '/api/message', function(req, res) {
var workspace = process.env.WORKSPACE_ID || '<workspace-id>';
if ( !workspace || workspace === '<workspace-id>' ) {
return res.json( {
'output': {
'text': 'The app has not been configured with a <b>WORKSPACE_ID</b> environment variable. Please refer to the ' +
'README documentation on how to set this variable. <br>' +
'Once a workspace has been defined the intents may be imported from ' +
'here in order to get a working application.'
}
} );
}
var payload = {
workspace_id: workspace,
context: {},
input: {}
};
if ( req.body ) {
if ( req.body.input ) {
payload.input = req.body.input;
}
if ( req.body.context ) {
// The client must maintain context/state
payload.context = req.body.context;
}
}
// Send the input to the conversation service
conversation.message( payload, function(err, data) {
if ( err ) {
return res.status( err.code || 500 ).json( err );
}
return res.json( updateMessage( payload, data ) );
} );
} );
/**
* Updates the response text using the intent confidence
* #param {Object} input The request to the Conversation service
* #param {Object} response The response from the Conversation service
* #return {Object} The response with the updated message
*/
function updateMessage(input, response) {
var responseText = null;
var id = null;
if ( !response.output ) {
response.output = {};
} else {
if ( logs ) {
// If the logs db is set, then we want to record all input and responses
id = uuid.v4();
logs.insert( {'_id': id, 'request': input, 'response': response, 'time': new Date()});
}
return response;
}
if ( response.intents && response.intents[0] ) {
var intent = response.intents[0];
// Depending on the confidence of the response the app can return different messages.
// The confidence will vary depending on how well the system is trained. The service will always try to assign
// a class/intent to the input. If the confidence is low, then it suggests the service is unsure of the
// user's intent . In these cases it is usually best to return a disambiguation message
// ('I did not understand your intent, please rephrase your question', etc..)
if ( intent.confidence >= 0.75 ) {
responseText = 'I understood your intent was ' + intent.intent;
} else if ( intent.confidence >= 0.5 ) {
responseText = 'I think your intent was ' + intent.intent;
} else {
responseText = 'I did not understand your intent';
}
}
response.output.text = responseText;
if ( logs ) {
// If the logs db is set, then we want to record all input and responses
id = uuid.v4();
logs.insert( {'_id': id, 'request': input, 'response': response, 'time': new Date()});
}
return response;
}
if ( cloudantUrl ) {
// If logging has been enabled (as signalled by the presence of the cloudantUrl) then the
// app developer must also specify a LOG_USER and LOG_PASS env vars.
if ( !process.env.LOG_USER || !process.env.LOG_PASS ) {
throw new Error( 'LOG_USER OR LOG_PASS not defined, both required to enable logging!' );
}
// add basic auth to the endpoints to retrieve the logs!
var auth = basicAuth( process.env.LOG_USER, process.env.LOG_PASS );
// If the cloudantUrl has been configured then we will want to set up a nano client
var nano = require( 'nano' )( cloudantUrl );
// add a new API which allows us to retrieve the logs (note this is not secure)
nano.db.get( 'car_logs', function(err) {
if ( err ) {
console.error(err);
nano.db.create( 'car_logs', function(errCreate) {
console.error(errCreate);
logs = nano.db.use( 'car_logs' );
} );
} else {
logs = nano.db.use( 'car_logs' );
}
} );
// Endpoint which allows deletion of db
app.post( '/clearDb', auth, function(req, res) {
nano.db.destroy( 'car_logs', function() {
nano.db.create( 'car_logs', function() {
logs = nano.db.use( 'car_logs' );
} );
} );
return res.json( {'message': 'Clearing db'} );
} );
// Endpoint which allows conversation logs to be fetched
app.get( '/chats', auth, function(req, res) {
logs.list( {include_docs: true, 'descending': true}, function(err, body) {
console.error(err);
// download as CSV
var csv = [];
csv.push( ['Question', 'Intent', 'Confidence', 'Entity', 'Output', 'Time'] );
body.rows.sort( function(a, b) {
if ( a && b && a.doc && b.doc ) {
var date1 = new Date( a.doc.time );
var date2 = new Date( b.doc.time );
var t1 = date1.getTime();
var t2 = date2.getTime();
var aGreaterThanB = t1 > t2;
var equal = t1 === t2;
if (aGreaterThanB) {
return 1;
}
return equal ? 0 : -1;
}
} );
body.rows.forEach( function(row) {
var question = '';
var intent = '';
var confidence = 0;
var time = '';
var entity = '';
var outputText = '';
if ( row.doc ) {
var doc = row.doc;
if ( doc.request && doc.request.input ) {
question = doc.request.input.text;
}
if ( doc.response ) {
intent = '<no intent>';
if ( doc.response.intents && doc.response.intents.length > 0 ) {
intent = doc.response.intents[0].intent;
confidence = doc.response.intents[0].confidence;
}
entity = '<no entity>';
if ( doc.response.entities && doc.response.entities.length > 0 ) {
entity = doc.response.entities[0].entity + ' : ' + doc.response.entities[0].value;
}
outputText = '<no dialog>';
if ( doc.response.output && doc.response.output.text ) {
outputText = doc.response.output.text.join( ' ' );
}
}
time = new Date( doc.time ).toLocaleString();
}
csv.push( [question, intent, confidence, entity, outputText, time] );
} );
res.csv( csv );
} );
} );
}
/************************************************
* Text-to-Speech services
************************************************/
/**
* Pipe the synthesize method
*/
app.get('/api/synthesize', (req, res, next) => {
const transcript = textToSpeech.synthesize(req.query);
transcript.on('response', (response) => {
if (req.query.download) {
if (req.query.accept && req.query.accept === 'audio/wav') {
response.headers['content-disposition'] = 'attachment; filename=transcript.wav';
} else {
response.headers['content-disposition'] = 'attachment; filename=transcript.ogg';
}
}
});
transcript.on('error', next);
transcript.pipe(res);
});
// Return the list of voices
app.get('/api/voices', (req, res, next) => {
textToSpeech.voices(null, (error, voices) => {
if (error) {
return next(error);
}
res.json(voices);
});
});
require('./config/error-handler')(app);
module.exports = app;
tts-custom.js(client side):
function text_to_speech(text) {
console.log(text);
// text = '<express-as type="GoodNews">'+text+'</express-as>';
text = encodeURIComponent(text);
console.log(text);
$.ajax({
method: 'GET',
url: '/api/synthesize?voice=en-US_AllisonVoice&download=true&text='+text,
dataType: 'native',
xhrFields: {
responseType: 'blob'
},
success: function(blob) {
var url = (URL || webkitURL).createObjectURL(blob);
$('#audio').attr('src', url);
$('#audio').attr('type', 'audio/ogg;codecs=opus');
}
})
}
chat.html:
<html>
<head>
<title> Chat </title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta property="og:image" content="conversation.svg" />
<meta property="og:title" content="Conversation Chat Simple" />
<meta property="og:description" content="Sample application that shows how to use the Watson Assistant API to identify user intents"
/>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="css/app.css">
<!-- <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.1/css/font-awesome.min.css" /> -->
<link rel="stylesheet" href="css/speech-input.css">
<script src="js/conversation.js"></script>
<!-- <script src="js/bundle.js"></script>
-->
<style type="text/css">
#result{
height: 200px;
border: 1px solid #ccc;
padding: 10px;
box-shadow: 0 0 10px 0 #bbb;
margin-bottom: 30px;
font-size: 14px;
line-height: 25px;
font-family: verdana;
}
button{
font-size: 20px;
position: absolute;
bottom: 10%;
right: 10%;
}
</style>
<style>
.mystyle {
display:none;
}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js" integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ=" crossorigin="anonymous"></script>
<script src="js/tts-custom.js"></script>
</head>
<body>
<!-- <div id="contentParent" class="responsive-columns-wrapper"> -->
<div id="view-change-button" class="button" onclick="hideChat(this)">
<img class="option full" src="../img/Chat Button.png">
<img class="option not-full" src="../img/Code Button.png">
</div>
<div id="chat-column-holder" class="responsive-column content-column">
<div class="chat-column">
<div id="scrollingChat"></div>
<label for="textInput" class="inputOutline">
<input id="textInput" class= "text" lang="es" placeholder="Type something" type="text" onkeydown="ConversationPanel.inputKeyDown(event, this, false)">
<!-- add this to class in textInput to put back google mic:, speech-input -->
</label>
<audio autoPlay="true" id="audio"
className="audio"
controls="controls">
Your browser does not support the audio element.
</audio>
<span id="microphone"></span>
</div>
</div>
<!-- PAYLOAD DON'T TOUCH/FOR TEXT->JSON -->
<div id="payload-column" class="fixed-column content-column">
<div id="payload-request" class="payload"></div>
<div id="payload-response" class="payload"></div>
</div>
<!-- SCRIPTS -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="js/jquery-ajax-native.js"></script>
<script type="text/javascript" src="js/Microphone.js"></script>
<script type="text/javascript" src="js/SpeechToText.js"></script>
<script type="text/javascript" src="js/speechsearch.js"></script>
<script src="js/hideChat.js"></script>
<script src="js/speech-input.js"></script>
<script src="js/common.js"></script>
<script src="js/api.js"></script>
<script src="js/payload.js"></script>
<script src="js/global.js"></script>
<script src="js/analytics.js"></script>
</body>
</html>
I'm not sure what to do but as the ajax is called and jquery is used in client side js, help is appreciated.

using elasticsearch.js is no result

I want show elastic search data on web page that using angular js.
however, not bring data from elasticsearch with that message
Is there anything I need to add or fix in my code?
if anyone answers to me I really appreciate
I have attached an execution screen.
thank you.
Execution screen:
enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController"></div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'http://localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
"match_all" : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
}).catch(function (err) {
if (err.status === 404) {
alert("error 404" );
} else {
alert("error : " + err );
}
});
});
</script>
</body>
</html>

Module unrecognised in Angular while using Node & Mongo

Working on a primitive enough MEAN-stack project.
When I run the application, the data-binding fails as the module which makes the association between my View and Backend(makes the http connection to my DB) never gets instantiated, and goes unrecognised.
Following error message appears in the console
[$injector:modulerr] Failed to instantiate module moviesApp due to:
Error: [$injector:nomod] Module 'moviesApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Error message is fairly understandable. I seem to have incorrectly(or not at all) created the link between the view "MoviesList.html" and the file containing the module I mentioned above (moviesApp), in the file "Movies.js".
Movies.js makes use of a factory. I've checked the general syntax(can't see how incorrect code inside the actual factory would cause the module to go unrecognised). Having written a basic factory before on jsfiddle, i'm confident that the syntax should be fine. https://jsfiddle.net/Sheepy99/4wmd3zd0/ (granted I chained the factory in that example, but it's the same general premise)
Before I post the rest of my code, it's based off of the example contained here: http://www.dotnetcurry.com/nodejs/1032/nodejs-apps-in-visual-studio-mean-stack
Some of my code is different due to differing versions, and some bits being deprecated since the author published the article(also wondering why he consistently uses double double-quotes).
Any ambiguity or loose ends, ask away.
MoviesList.html
<html>
<!--<meta charset="UTF-8">-->
<title>Node-Express Movie List</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!--<link rel="stylesheet" href="/styles/site.css">-->
 
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<!--<script src="/scripts/controller.js"></script>
<script src="/scripts/movies.js"></script>-->
<script src="../public/scripts/movies.js"></script>
<script src="../public/scripts/controller.js"></script>
</head>
<body>
<div class="container">
     <!--<div class="text-center" ng-app="moviesApp" ng-controller="MoviesCtrl">-->
<div class="text-center" ng-app="moviesApp" ng-controller="MoviesCtrl">
         <h1>Node-Express Movie List</h1>
         <div class="col-md-12" control-group="">
             <input type="text" style="width: 200px;" ng-model="newMovieText">
             <button id="btnAddTodo" class="btn" style="margin: 2px;" ng-click="addMovie()" ng-disabled="newMovieText">Add Movie</button>
         </div>
 
         <div class="col-md-5" sticky-note="">
             <h3 class="text-center">Released Movies</h3>
             <!--<div class="col-md-5" rowmargin="" todoitem="" ng-repeat="movie" in="" movies="" |="" filter:{released:true}"="">-->
<div class="col-md-5" rowmargin="" todoitem="" ng-repeat="movie" in="" movies="" filter:{released:true}>
                 <div class="thumbnail">
                     <input type="checkbox" ng-model="movie.watched" ng-change="movieWatched(movie)">
                      
                     <span ng-class="{watchedMovie: movie.watched}">{{movie.name}}</span>
                 </div>
             </div>
         </div>
 
         <div class="col-md-5" sticky-note="">
             <h3 class="text-center">Coming Up...</h3>
             <div class="col-md-5" rowmargin="" todoitem="" ng-repeat="movie" in="" movies="" filter:{released:false}>
                 <div class="thumbnail">
                     {{movie.name}}
                     <br>
                     <br>
                     <input type="button" value="Released!" class="btn btn-success" btn-link="" released-button="" ng-click="movieReleased(movie)" style="">
                 </div>
             </div>
         </div>
     </div>
</div>
</body>
</html>
movies.js
var app = angular.module('moviesApp', []);
 
app.factory('moviesCRUD', function ($http, $q) {
    function getAllMovies() {
        var deferred = $q.defer();
 
        $http.get('/api/movies').then(function (result) {
            deferred.resolve(result.data);
        }, function (error) {
            deferred.reject(error);
        });
 
        return deferred.promise;
    }
 
    function addMovie(newMovie) {
        var deferred = $q.defer();
 
        $http.post('/api/movies', newMovie).then(function (result) {
            deferred.resolve(result.data.movie);
        }, function (error) {
            deferred.reject(error);
        });
 
        return deferred.promise;
    }
 
    function modifyMovie(updatedMovie) {
        var deferred = $q.defer();
 
        $http.put('/api/movies/' + updatedMovie._id, updatedMovie).then(function (data) {
            deferred.resolve(data);
        }, function (error) {
            deferred.reject(error);
        });
 
        return deferred.promise;
    }
 
    return {
        getAllMovies: getAllMovies,
        addMovie: addMovie,
        modifyMovie: modifyMovie
    };
});
mongoOperations.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//http://stackoverflow.com/questions/24908405/mongoose-and-new-schema-returns-referenceerror-schema-is-not-defined
//link recommends use of what's on line 2 as a solution
mongoose.Promise = global.Promise; //not using promises, this line removes a default setting and also gets rid of a warning about promises
mongoose.connect('mongodb://localhost/moviesDb');
var db = mongoose.connection;
//var movieSchema = mongoose.Schema({ *I shouldn't need this because i've declared "require('mongoose')"
var movieSchema = new Schema({
name: String, //doesn't like if I have spaces on each new line, before the use of characters
released: Boolean,
watched: Boolean
});
var MovieModel = mongoose.model('movie', movieSchema);
db.on('error', console.error.bind(console, "connection error"));
db.once('open', function () {
//console.log("moviesDb is open...");  
MovieModel.find().exec(function (error, results) {
if (results.length === 0) {
MovieModel.create({ name: "The Amazing Spider-Man 2", released: true, watched: false });
MovieModel.create({ name: "The Other Woman", released: true, watched: true });
MovieModel.create({ name: "Shaadi ke Side Effects", released: false, watched: false });
MovieModel.create({ name: "Walk of Shame", released: true, watched: false });
MovieModel.create({ name: "Lucky Kabootar", released: false, watched: false });
}
});
});
exports.fetch = function (request, response) {
MovieModel.find().exec(function (err, res) {
if (err) {
response.send(500, { error: err });
}
else {
response.send(res);
}
});
};
exports.add = function (request, response) {
var newMovie = { name: request.body.name, released: false, watched: false };
MovieModel.create(newMovie, function (addError, addedMovie) {
if (addError) {
response.send(500, { error: addError });
}
else {
response.send({ success: true, movie: addedMovie });
}
});
};
exports.modify = function (request, response) {
var movieId = request.params.movieId;
MovieModel.update({ _id: movieId }, { released: request.body.released, watched: request.body.watched }, { multi: false },
function (error, rowsAffected) {
if (error) {
response.send(500, { error: error });
}
else if (rowsAffected == 0) {
response.send(500, { error: "No rows affected" });
}
else {
response.send(200);
}
}
);
};
server.js
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var path = require("path");
 
var port = process.env.port || 1337;
 
var app = express();
//app.use(bodyParser()); //getting deprecated warning in shell when using this specific line
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(bodyParser.json()); used in stackoverflow solution, can see potential benefit, but isn't helping
var mongoOps = require('./server/MongoOperations.js');
 
app.get('/', function (request, response) {
//response.sendfile("views/MoviesList.html");
//response.sendFile("views/MoviesList.html");
response.sendFile("views/MoviesList.html", { "root": __dirname });
});
app.get('/api/list', function (request, response) {
response.send([{ id: 1, name: "charlie" }, { "id": 2, "name": "ward" }]);
//'Hello World!');
});
app.get('/api/movies', mongoOps.fetch);
 
app.post('/api/movies', mongoOps.add);
 
app.put('/api/movies/:movieId', mongoOps.modify);
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port);
controller.js
app.controller('MoviesCtrl', function ($scope, moviesCRUD) {
    $scope.released = { released: true };
    $scope.notReleased = { released: false };
     
    function init() {
        moviesCRUD.getAllMovies().then(function (movies) {
            $scope.movies = movies;
        }, function (error) {
            console.log(error);
        });       
    }
 
    $scope.movieReleased = function (movie) {
 
        moviesCRUD.modifyMovie({ _id: movie._id, name: movie.name, released: true, watched: movie.watched })
                  .then(function (result) {
                      if (result.status === 200) {
                          movie.released = true;
                      }
                  }, function (error) {
                      console.log(error);
                  });       
    };
 
    $scope.movieWatched = function (movie) {
        moviesCRUD.modifyMovie(movie)
                  .then(function (result) {
                      if (result.status === 200) {
                          console.log("Movie updated");
                      }
                  }, function (error) {
                      movie.watched = !movie.watched;
                  });       
    };
 
    $scope.addMovie = function () {
        moviesCRUD.addMovie({ name: $scope.newMovieText }).then(function (newMovie) {
            $scope.movies.push(newMovie);
            $scope.newMovieText = "";
        }, function (error) {
            console.log(error);
        });       
    };
 
    init();
});
Also, much of my html is being rendered as question marks inside diamonds. This has me absolutely puzzled. Just thought i'd put that out there.
As a noobie, any brief general suggestions would be welcomed, as in adjustments to my code for readability, or approach.
I made a few changes to your code to get Angular to "compile" it, but I didn't have the code for the controller so I could not finish setting it up. But if you look at this plunk, you can see my changes.
<html ng-app="moviesApp">
<head>
<!--<meta charset="UTF-8">-->
<title>Node-Express Movie List</title>
<script data-require="angular.js#1.6.1" data-semver="1.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<!--<link rel="stylesheet" href="/styles/site.css">-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<!--<script src="/scripts/controller.js"></script>
<script src="/scripts/movies.js"></script>-->
<script src="movies.js"></script>
<!--<script src="../public/scripts/controller.js"></script>-->
</head>
You had issues with the placement of the HEAD in the HTML, plus you bootstrapped the application in the first DIV, which I guess it could work, but it is very non-standard. You start your application in a Plunk or Codepen to make it easier on yourself.
Have fun.
Figured it out:
Because I have the following line near the bottom of server.js, my directory automatically starts of public, when specifying directives for external modules(in this case controller.js and movies.js.
Therefore, my directives were incorrect.
As for the strange diamonds I had mentioned at the bottom of my question, it was due to my files being automatically being saved as ASCII when I created them, when they should've been UTF-8.
An annoying and pedantic problem, but i'm sure someone will eventually find some help from this.
app.use(express.static(path.join(__dirname, 'public')));

Categories