Iterate over Json data and print in EJS - javascript

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo
^^reference of data
Here some data that I am trying to use. I made my own Api key and am using it in my routes.
var router = require('express').Router();
const stockApi = 'YOUR_API_KEY';
router.get("/", function(req, res) {
var request = require('request');
request('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey='+stockApi, function (error, response, body) {
var json = JSON.parse(body)
if (error) {
console.log(error)
} else {
console.log(json)
res.render("home/home", {data:json});
}
});
});
module.exports = router;
So I had parsed my data and passed it into the response.render as 'data'.
Here is where I am a little confused. I am trying to print the 'Meta Data' and 'Time Series' into an ejs template. But it will throw an error saying forEach is not a function. I am a little new to using Json data in ejs. Here is my template that I am just trying to print one piece of data.
<body>
<%-include('../partials/navbar')%>
<div class="container">
<div class="row mt-4">
<div class="col">
<% data.forEach((stock) => { %>
<p><%=stock.Meta_Data %></p>
<%})%>
</div>
</div>
</div>
</body>
Also when I make the request I do see all the data in the console. I just can't seem to print the objects that I want.

You can do something like this with for...in
var obj = {"Meta Data":{"1. Information":"Intraday (1min) prices and volumes","2. Symbol":"MSFT","3. Last Refreshed":"2018-04-30 16:00:00","4. Interval":"1min","5. Output Size":"Compact","6. Time Zone":"US/Eastern"},"Time Series (1min)":{"2018-04-30 16:00:00":{"1. open":"93.6600","2. high":"93.7600","3. low":"93.4800","4. close":"93.5200","5. volume":"6710769"},"2018-04-30 15:59:00":{"1. open":"93.7100","2. high":"93.7100","3. low":"93.6100","4. close":"93.6600","5. volume":"259169"},"2018-04-30 15:58:00":{"1. open":"93.6700","2. high":"93.7100","3. low":"93.6600","4. close":"93.7050","5. volume":"171998"},"2018-04-30 15:57:00":{"1. open":"93.6900","2. high":"93.7100","3. low":"93.6150","4. close":"93.6600","5. volume":"198574"},"2018-04-30 15:56:00":{"1. open":"93.6500","2. high":"93.7300","3. low":"93.6500","4. close":"93.6966","5. volume":"187325"},"2018-04-30 15:55:00":{"1. open":"93.5800","2. high":"93.6600","3. low":"93.5500","4. close":"93.6500","5. volume":"134861"},"2018-04-30 15:54:00":{"1. open":"93.6650","2. high":"93.6900","3. low":"93.5800","4. close":"93.5800","5. volume":"116057"},"2018-04-30 15:53:00":{"1. open":"93.6850","2. high":"93.7400","3. low":"93.6500","4. close":"93.6650","5. volume":"149629"},"2018-04-30 15:52:00":{"1. open":"93.7700","2. high":"93.7800","3. low":"93.6700","4. close":"93.6900","5. volume":"182107"},"2018-04-30 15:51:00":{"1. open":"93.9700","2. high":"94.0100","3. low":"93.7692","4. close":"93.7692","5. volume":"271349"},"2018-04-30 15:50:00":{"1. open":"94.0850","2. high":"94.1185","3. low":"93.8200","4. close":"93.9600","5. volume":"143081"},"2018-04-30 15:49:00":{"1. open":"94.0400","2. high":"94.1000","3. low":"94.0400","4. close":"94.0899","5. volume":"66721"},"2018-04-30 15:48:00":{"1. open":"94.1050","2. high":"94.1100","3. low":"94.0100","4. close":"94.0200","5. volume":"128293"},"2018-04-30 15:47:00":{"1. open":"94.1250","2. high":"94.1700","3. low":"94.1050","4. close":"94.1050","5. volume":"89355"},"2018-04-30 15:46:00":{"1. open":"94.1350","2. high":"94.2900","3. low":"94.1100","4. close":"94.1250","5. volume":"199854"},"2018-04-30 15:45:00":{"1. open":"94.1600","2. high":"94.2200","3. low":"94.1300","4. close":"94.1350","5. volume":"141196"},"2018-04-30 15:44:00":{"1. open":"94.0950","2. high":"94.2000","3. low":"94.0900","4. close":"94.1700","5. volume":"117068"},"2018-04-30 15:43:00":{"1. open":"94.1250","2. high":"94.1500","3. low":"94.0700","4. close":"94.1000","5. volume":"69581"},"2018-04-30 15:42:00":{"1. open":"94.1550","2. high":"94.1600","3. low":"94.0950","4. close":"94.1200","5. volume":"59339"},"2018-04-30 15:41:00":{"1. open":"94.1650","2. high":"94.1800","3. low":"94.1150","4. close":"94.1550","5. volume":"104516"},"2018-04-30 15:40:00":{"1. open":"94.0701","2. high":"94.1800","3. low":"94.0700","4. close":"94.1650","5. volume":"85866"},"2018-04-30 15:39:00":{"1. open":"94.1200","2. high":"94.1281","3. low":"94.0600","4. close":"94.0750","5. volume":"60088"},"2018-04-30 15:38:00":{"1. open":"94.0900","2. high":"94.1400","3. low":"94.0800","4. close":"94.1250","5. volume":"57689"},"2018-04-30 15:37:00":{"1. open":"94.1250","2. high":"94.1400","3. low":"94.0300","4. close":"94.0950","5. volume":"71865"},"2018-04-30 15:36:00":{"1. open":"94.1750","2. high":"94.2100","3. low":"94.1200","4. close":"94.1300","5. volume":"69678"},"2018-04-30 15:35:00":{"1. open":"94.1000","2. high":"94.2300","3. low":"94.0900","4. close":"94.1700","5. volume":"145388"},"2018-04-30 15:34:00":{"1. open":"94.0350","2. high":"94.1000","3. low":"94.0100","4. close":"94.0900","5. volume":"69089"},"2018-04-30 15:33:00":{"1. open":"94.0050","2. high":"94.0600","3. low":"94.0000","4. close":"94.0300","5. volume":"44944"},"2018-04-30 15:32:00":{"1. open":"94.0000","2. high":"94.0618","3. low":"93.9900","4. close":"94.0000","5. volume":"50624"},"2018-04-30 15:31:00":{"1. open":"93.9300","2. high":"94.0000","3. low":"93.9300","4. close":"94.0000","5. volume":"46465"},"2018-04-30 15:30:00":{"1. open":"93.9400","2. high":"93.9900","3. low":"93.9300","4. close":"93.9400","5. volume":"69917"},"2018-04-30 15:29:00":{"1. open":"93.8700","2. high":"93.9300","3. low":"93.8500","4. close":"93.9300","5. volume":"38623"},"2018-04-30 15:28:00":{"1. open":"93.8200","2. high":"93.8900","3. low":"93.8050","4. close":"93.8700","5. volume":"26722"},"2018-04-30 15:27:00":{"1. open":"93.8300","2. high":"93.8500","3. low":"93.7900","4. close":"93.8239","5. volume":"27912"},"2018-04-30 15:26:00":{"1. open":"93.8250","2. high":"93.8500","3. low":"93.8200","4. close":"93.8300","5. volume":"24261"},"2018-04-30 15:25:00":{"1. open":"93.8175","2. high":"93.8461","3. low":"93.7900","4. close":"93.8300","5. volume":"33380"},"2018-04-30 15:24:00":{"1. open":"93.9100","2. high":"93.9500","3. low":"93.7600","4. close":"93.8100","5. volume":"86405"},"2018-04-30 15:23:00":{"1. open":"93.9100","2. high":"93.9200","3. low":"93.8500","4. close":"93.9015","5. volume":"46606"},"2018-04-30 15:22:00":{"1. open":"94.0200","2. high":"94.0800","3. low":"93.8900","4. close":"93.9000","5. volume":"80331"},"2018-04-30 15:21:00":{"1. open":"94.0300","2. high":"94.0300","3. low":"93.9900","4. close":"94.0199","5. volume":"21440"},"2018-04-30 15:20:00":{"1. open":"93.9800","2. high":"94.0342","3. low":"93.9650","4. close":"94.0342","5. volume":"20556"},"2018-04-30 15:19:00":{"1. open":"93.9600","2. high":"93.9900","3. low":"93.9500","4. close":"93.9900","5. volume":"19247"},"2018-04-30 15:18:00":{"1. open":"93.9300","2. high":"93.9966","3. low":"93.9300","4. close":"93.9600","5. volume":"20679"},"2018-04-30 15:17:00":{"1. open":"94.0200","2. high":"94.0300","3. low":"93.9200","4. close":"93.9200","5. volume":"65818"},"2018-04-30 15:16:00":{"1. open":"94.0100","2. high":"94.1300","3. low":"93.9950","4. close":"94.0300","5. volume":"139065"},"2018-04-30 15:15:00":{"1. open":"94.0200","2. high":"94.0900","3. low":"94.0000","4. close":"94.0100","5. volume":"30109"},"2018-04-30 15:14:00":{"1. open":"94.0300","2. high":"94.0500","3. low":"94.0050","4. close":"94.0300","5. volume":"18015"},"2018-04-30 15:13:00":{"1. open":"94.0100","2. high":"94.0600","3. low":"93.9900","4. close":"94.0300","5. volume":"40470"},"2018-04-30 15:12:00":{"1. open":"93.9750","2. high":"94.0200","3. low":"93.9400","4. close":"94.0061","5. volume":"36967"},"2018-04-30 15:11:00":{"1. open":"93.9250","2. high":"94.0200","3. low":"93.9201","4. close":"93.9800","5. volume":"39671"},"2018-04-30 15:10:00":{"1. open":"93.9100","2. high":"93.9800","3. low":"93.9050","4. close":"93.9300","5. volume":"28209"},"2018-04-30 15:09:00":{"1. open":"93.9000","2. high":"94.0200","3. low":"93.9000","4. close":"93.9150","5. volume":"37855"},"2018-04-30 15:08:00":{"1. open":"93.9150","2. high":"93.9400","3. low":"93.8800","4. close":"93.9000","5. volume":"32684"},"2018-04-30 15:07:00":{"1. open":"93.8700","2. high":"93.9700","3. low":"93.8700","4. close":"93.9200","5. volume":"44537"},"2018-04-30 15:06:00":{"1. open":"93.7900","2. high":"93.8700","3. low":"93.7600","4. close":"93.8650","5. volume":"29812"},"2018-04-30 15:05:00":{"1. open":"93.8300","2. high":"93.8700","3. low":"93.7700","4. close":"93.7900","5. volume":"49564"},"2018-04-30 15:04:00":{"1. open":"93.7900","2. high":"93.8400","3. low":"93.7800","4. close":"93.8300","5. volume":"38744"},"2018-04-30 15:03:00":{"1. open":"93.8700","2. high":"93.8900","3. low":"93.7800","4. close":"93.7800","5. volume":"41179"},"2018-04-30 15:02:00":{"1. open":"93.8500","2. high":"93.9000","3. low":"93.8300","4. close":"93.8700","5. volume":"37526"},"2018-04-30 15:01:00":{"1. open":"93.8300","2. high":"93.8900","3. low":"93.7900","4. close":"93.8501","5. volume":"31866"},"2018-04-30 15:00:00":{"1. open":"93.8800","2. high":"93.9200","3. low":"93.8250","4. close":"93.8250","5. volume":"36569"},"2018-04-30 14:59:00":{"1. open":"93.8900","2. high":"93.9200","3. low":"93.8800","4. close":"93.8800","5. volume":"16199"},"2018-04-30 14:58:00":{"1. open":"93.9700","2. high":"93.9700","3. low":"93.8700","4. close":"93.8850","5. volume":"60618"},"2018-04-30 14:57:00":{"1. open":"94.0100","2. high":"94.0400","3. low":"93.9600","4. close":"93.9700","5. volume":"16716"},"2018-04-30 14:56:00":{"1. open":"94.0099","2. high":"94.0700","3. low":"93.9700","4. close":"94.0000","5. volume":"32260"},"2018-04-30 14:55:00":{"1. open":"93.9900","2. high":"94.0900","3. low":"93.9700","4. close":"94.0099","5. volume":"38314"},"2018-04-30 14:54:00":{"1. open":"94.0600","2. high":"94.0600","3. low":"93.9700","4. close":"93.9900","5. volume":"37277"},"2018-04-30 14:53:00":{"1. open":"94.0700","2. high":"94.0800","3. low":"93.9500","4. close":"94.0600","5. volume":"48356"},"2018-04-30 14:52:00":{"1. open":"94.0108","2. high":"94.0790","3. low":"93.9850","4. close":"94.0750","5. volume":"27780"},"2018-04-30 14:51:00":{"1. open":"94.0100","2. high":"94.0600","3. low":"94.0000","4. close":"94.0200","5. volume":"23033"},"2018-04-30 14:50:00":{"1. open":"93.9700","2. high":"94.0200","3. low":"93.9400","4. close":"94.0020","5. volume":"18227"},"2018-04-30 14:49:00":{"1. open":"93.8900","2. high":"93.9800","3. low":"93.8850","4. close":"93.9800","5. volume":"22587"},"2018-04-30 14:48:00":{"1. open":"93.8800","2. high":"93.9199","3. low":"93.8410","4. close":"93.8900","5. volume":"46588"},"2018-04-30 14:47:00":{"1. open":"93.9150","2. high":"93.9300","3. low":"93.8200","4. close":"93.8800","5. volume":"40456"},"2018-04-30 14:46:00":{"1. open":"93.9400","2. high":"93.9800","3. low":"93.9100","4. close":"93.9100","5. volume":"15290"},"2018-04-30 14:45:00":{"1. open":"93.9250","2. high":"93.9700","3. low":"93.9250","4. close":"93.9439","5. volume":"12610"},"2018-04-30 14:44:00":{"1. open":"94.0000","2. high":"94.0000","3. low":"93.8700","4. close":"93.9234","5. volume":"42916"},"2018-04-30 14:43:00":{"1. open":"93.9550","2. high":"94.0400","3. low":"93.9500","4. close":"94.0010","5. volume":"64156"},"2018-04-30 14:42:00":{"1. open":"94.0150","2. high":"94.0400","3. low":"93.9400","4. close":"93.9500","5. volume":"36427"},"2018-04-30 14:41:00":{"1. open":"94.0150","2. high":"94.0500","3. low":"94.0050","4. close":"94.0200","5. volume":"21677"},"2018-04-30 14:40:00":{"1. open":"94.0750","2. high":"94.0800","3. low":"93.9900","4. close":"94.0100","5. volume":"45532"},"2018-04-30 14:39:00":{"1. open":"94.0400","2. high":"94.1700","3. low":"94.0400","4. close":"94.0700","5. volume":"44581"},"2018-04-30 14:38:00":{"1. open":"94.1000","2. high":"94.1100","3. low":"94.0200","4. close":"94.0350","5. volume":"30249"},"2018-04-30 14:37:00":{"1. open":"94.0700","2. high":"94.1150","3. low":"94.0400","4. close":"94.1050","5. volume":"40627"},"2018-04-30 14:36:00":{"1. open":"94.0800","2. high":"94.1200","3. low":"94.0400","4. close":"94.0700","5. volume":"25601"},"2018-04-30 14:35:00":{"1. open":"94.0200","2. high":"94.1250","3. low":"94.0200","4. close":"94.0900","5. volume":"45214"},"2018-04-30 14:34:00":{"1. open":"94.1200","2. high":"94.1900","3. low":"94.0000","4. close":"94.0100","5. volume":"74102"},"2018-04-30 14:33:00":{"1. open":"94.0316","2. high":"94.1200","3. low":"94.0200","4. close":"94.1200","5. volume":"32945"},"2018-04-30 14:32:00":{"1. open":"94.0850","2. high":"94.1400","3. low":"94.0200","4. close":"94.0350","5. volume":"29269"},"2018-04-30 14:31:00":{"1. open":"94.1300","2. high":"94.1450","3. low":"94.0800","4. close":"94.0800","5. volume":"32486"},"2018-04-30 14:30:00":{"1. open":"94.1200","2. high":"94.2300","3. low":"94.1150","4. close":"94.1400","5. volume":"46830"},"2018-04-30 14:29:00":{"1. open":"94.0800","2. high":"94.1500","3. low":"94.0750","4. close":"94.1100","5. volume":"39559"},"2018-04-30 14:28:00":{"1. open":"94.1450","2. high":"94.1600","3. low":"94.0600","4. close":"94.0700","5. volume":"30840"},"2018-04-30 14:27:00":{"1. open":"94.1200","2. high":"94.1750","3. low":"94.1050","4. close":"94.1400","5. volume":"36854"},"2018-04-30 14:26:00":{"1. open":"94.1100","2. high":"94.1900","3. low":"94.1050","4. close":"94.1250","5. volume":"27821"},"2018-04-30 14:25:00":{"1. open":"94.1350","2. high":"94.2200","3. low":"94.1000","4. close":"94.1200","5. volume":"37538"},"2018-04-30 14:24:00":{"1. open":"94.1550","2. high":"94.2100","3. low":"94.1250","4. close":"94.1300","5. volume":"36620"},"2018-04-30 14:23:00":{"1. open":"94.1900","2. high":"94.2450","3. low":"94.1400","4. close":"94.1550","5. volume":"38887"},"2018-04-30 14:22:00":{"1. open":"94.1000","2. high":"94.2200","3. low":"94.0700","4. close":"94.1900","5. volume":"61078"},"2018-04-30 14:21:00":{"1. open":"94.0000","2. high":"94.1270","3. low":"93.9939","4. close":"94.1000","5. volume":"41664"}}};
// This is for Meta Data
for (var meta_data in obj["Meta Data"]){
console.log(meta_data);
}
// This is for Time Series Data
for (var time_series in obj["Time Series (1min)"]){
console.log(time_series);
for(var time_series_data in obj["Time Series (1min)"][time_series]){
console.log(time_series_data);
}
}

Please install the npm package of Alpha vantage Wrapper
1.npm install --save alpha_vantage_api_wrapper for NPM
const express = require('express');
const app =express();
var Alpha = require('alpha_vantage_api_wrapper').Alpha; //Alpha Wrapper
var alpha = new Alpha('demo');
var stock_Dates = []; //Array Of Data
var stock_opens = [];
var stock_highs = [];
var stock_lows = [];
var stock_closes = [];
var stock_volumes = [];
app.get('/', function(req,res){
res.render('list', { query, stock_Dates, stock_opens, stock_highs, stock_lows, stock_closes, stock_volumes });
//Injected in to views
});
app.post('/', function(req,res) {
const query = req.body.stockName;
alpha.stocks.intraday(query) //Alpha Api-wrapper Function
.then((data) => {
const intraDay = (data['Time Series (5min)']);
for(var update in intraDay){
var stock_Date = update;
var stock_open = intraDay[update]['1. open']; //Narrowing the endpoints for accessing the req Data
var stock_high = intraDay[update]['2. high'];
var stock_low = intraDay[update]['3. low'];
var stock_close = intraDay[update]['4. close'];
var stock_volume = intraDay[update]['5. volume'];
stock_Dates.push(stock_Date); //Pushing the Data into the Array of Data
stock_opens.push(stock_open);
stock_highs.push(stock_high);
stock_lows.push(stock_low);
stock_closes.push(stock_close);
stock_volumes.push(stock_volume);
}
res.redirect('/'); //Redirects To the hamepage
})
.catch((err) => {
// Handle the error
console.log(err); //Logs error if any
});
});

Related

How is it possible that piece of code that was working is now ignored?

I have coded a ajax based "JS TABS" containing .JSON file like 10 months ago, now wanted to reuse it, and can't find out why it's not working. I haven't touched it since and don't know where is the bug.
When i click the button to render products nothing prints out - except console telling me: items is undefined = so i moved it inside function changeCategoryItems(categoryId) { } well no errors but nothing renders...can someone help me ?
Here is a codepen reference of what i mean: https://codepen.io/Contemplator191/pen/WNwgypY
And this is JSON : https://api.jsonbin.io/b/5f634e0c302a837e95680846
If codepen is not suitable/allowed here is whole JS for that
let items = [];
const buttons = document.querySelectorAll('button');
const wrapper = document.querySelector('section.products');
buttons.forEach(function (button) {
button.addEventListener('click',event => {
changeCategoryItems(event.target.dataset.category);
});
});
function changeCategoryItems(categoryId) {
let items = [];
const buttons = document.querySelectorAll('button');
const wrapper = document.querySelector('section.products');
const viewItems = (categoryId == 0 ) ? items : items.filter(item => item.category == categoryId);
wrapper.innerHTML = "";
viewItems.forEach(item => {
const div = document.createElement('div');
div.setAttribute("class", "product");
div.innerHTML = createItem(item);
wrapper.appendChild(div);
});
};
function createItem(item) {
return `
<div class="product__img">
<img src="${item.img}" class="">
</div>
<div class="product__name _tc">
<h4 class="">${item.heading}</h4>
</div>
<div class="text-desc product__desc">
<p class="">${item.description}</p>
</div>
<div class="product__bottom-content">
<span class="product__info">${item.info}</span>
${item.btn}
</div>
`
}
fetch('https://api.jsonbin.io/b/5f634e0c302a837e95680846')
.then(function (res) { return res.json() })
.then(function (data) {
items = data.items;
changeCategoryItems(1);
});`
In your fetch you're trying to assign data.items to the items variable but the api doesn't return data with an items node so items is undefined. It's possible the api changed their return format since the last time you used it which would explain why it worked previously.
this seems to fix it
.then(function (data) {
items = data;
changeCategoryItems(1);
});
Your issue is in this line:
items = data.items;
Now, the returned value is an array, hence you can use it as it is.
The updated codepen

How to get value from dynamically generated <option> <select> express ejs

First of all I thank you for reading and making an attempt to my problem.
I dynamically rendered my {dropdown} but i was unable to get the selected value at my back-end.
on my form i am also getting photo and the name of suite is dynamically rendered.
Code below if i am doing something incorrect.
Lang - Javascript
FW - Express Js
Template - EJS
I have body-parse and set to true.
Issue i cannot get selected value to my back-end using POST request (undefined or null).
But if i use GET as the action & Request i do get the selected value.
Thank you again. If i am not clear please, i will explain clearly. I am newly NODE JS AND EXPRESS.
-Front-end
<form class="ui form" action="admin/uploadphoto" method="POST" enctype="multipart/form-data">
<h2 class=" ui dividing header" style="text-align: center;">Add Images to suites</h2>
<div class="two fields">
<div class="field">
<label>Add Suites Images</label>
<input name="suiteimage" type="file">
</div>
<div class="field">
<label>Suites*</label>
<select name="suiteselected" class="ui dropdown">
<% suites.forEach(function(suite) { %>
<option name = "suiteid" value="<%= suite.suite_name %>"><%= suite.suite_name %></option>
<% })%>
</select>
</div>
</div>
<input type="submit" class="ui button" tabindex="0" value="Save New Suite">
</form>
Back-end
const uuid = require("uuid/v4");
const { Pool } = require("pg");
const multer = require("multer");
// Insert photo and selected value from dropdown (options)
const PostPhoto = (req, res) => {
var suiteimage;
const suite_photo_id = uuid();
const {suiteselected} = req.body;
console.log( suiteselected + " --ID") //Here i am testing if selected valued is passed
// this is my multer function to config where i need to store my photo path
upload(req, res, err => {
suiteimage = req.file.path;
if (err) {
console.log(err);
} else {
console.log(suiteimage);
}
});
..... //my database query to save my post....
};
-route
router.post ('/uploadphoto', service.PostPhoto);
``
I have figured out the solution to this, body-parse should be required and extended true.
when having text and image as 1 form to be posted to the back-end make sure
Your image function (upload) is inside the req,res function or the values will be undefine or null.
if you need more explanation to comment.
//my post for image and text function
const PostPhoto = (req, res) => {
const suite_photo_id = uuid();
upload(req, res, function(err) {
const {suiteselected} = req.body;
console.log(req.file);
var imagePath = req.file.path.replace(/^public\//, '');
console.log( suiteselected + " --ID")
console.log(imagePath);
pool.query(
"INSERT INTO suite_photos (suite_photo_id,suite_photo,suite_id) VALUES($1,$2,$3)",
[suite_photo_id, imagePath,suiteselected],
(error, result) => {
if (error) {
throw error;
} else{
console.log(result);
res.redirect("/admin");
}
}
);
});
};
That's all that changed.
Thank you all!!!

How to send values of input elements ( text / select / radio ) to node.js server

How can I receive the values of the radio buttons and a select list and put it on the file name?
This is the function that will be using the values :
router.get('/import', function(req, res, next) {
var csvStream = fastCsv()
.on('data', function(data) {
var report = new csvUploads({
jirakey: data[0],
status: data[1],
priority: data[2],
validity: data[3],
type: data[4],
month: data[5],
defectCategory: data[6],
defectSubCategory: data[7]
});
report.save(function(error) {
console.log(report);
if (error) {
throw error;
}
});
}).on('end', function() {});
const request = req.body;
let month = req.month;
let team = req.team;
const filename = month + ' - ' + team + '.csv';
console.log(res.send(filename));
const csvFilePath = "./uploads/" + filename;
var stream = fs.createReadStream(csvFilePath);
stream.pipe(csvStream);
res.json({
success: 'Data imported successfully',
status: 200
});
});
Currently this is what I have tried, it returns undefined in both the radio button and select list value
instead of
const request = req.body;
let month = req.month;
let team = req.team;
try
const request = req.body;
let month = request.month;
let team = request.team;
I would suggest that you simply serve the view (importer.html) and use it as as a client for your server (using POST), that way you may interact with the server and display the changes/retrieved data back in the client.
You will be needing :
GET route for displaying the "client".
POST route for using the "client submitted data and crafting an
adecuate response".
Client logic for doing something when the server replies.
Hope this proof-of-concept (working example) will help you understand better :
SERVER CODE
const express = require('express'); global.app = express()
const bodyParser = require('body-parser')
/* SETUP SERVER CONFIG OPTIONS */
const CONF = {
"htmlDir":__dirname+"/",
"port":3000
}
//----------------------------------------------------------
//.: Server StratUp : Setup Event Handling :.
function InitializeServer(){
console.log("[~] starting ...")
//:[EXPRESS]:MiddleWare
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
//:[EXPRESS]:Router (GET Requests)
app.get("/",RenderImport)
//:[EXPRESS]:Router (POST Requests)
app.post("/import",ImportRequest)
//:[EXPRESS]:Start
app.listen(CONF.port,onSuccessfullStartup)
}
/* Callback example for express successfully listening */
const onSuccessfullStartup=()=>{
console.log("[i] ready & listening","\n http://localhost:"+CONF.port+"/")
}
//----------------------------------------------------------
/* ROUTER EVENT FUNCTIONS : */
const RenderImport=(req,res)=>{res.sendFile(CONF.htmlDir+"importer.html")}
const ImportRequest=(req,res)=>{
console.log("[POST] /import")
console.log(req.body)
if(req.body.stringExample&&req.body.selectExample&&req.body.radioExample){
console.log(" > valid POSTData")
var doSomethingNow={"status":"OK","data":[1,2,3,4,5]}
res.json(doSomethingNow)
}else{
console.log(" > invalid POSTData")
res.json({"status":"ERROR"})
}
}
//----------------------------------------------------------
InitializeServer() // We can now start the server
CLIENT CODE (importer.html)
<html><head><title>INDEX</title></head><body>
<center>
<h1>SEND DATA TO SERVER</h1>
<form name="theForm">
<!-- String Example -->
<input name="stringExample" type="text"></input>
<!-- Select Example -->
<select name="selectExample">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<select>
<!-- Radio Example -->
<input type="radio" name="radioExample" value="a" checked> One
<input type="radio" name="radioExample" value="b" > Other
<input type="radio" name="radioExample" value="c" > Another
</form>
<button onclick="SEND()">SEND</button>
</center>
<script>
function SEND(){
var newXHR = new XMLHttpRequest();
newXHR.addEventListener("load",RequestDone);
newXHR.open("POST","/import");
newXHR.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
//Fetch Form Data
var form = document.theForm;
var inputx = form.elements["stringExample"];
var select = form.elements["selectExample"];
var radios = form.elements["radioExample"];
//Data for POST
var JSONObj = {}
JSONObj.stringExample = inputx.value
JSONObj.selectExample = select.value
JSONObj.radioExample = radios.value
console.log(JSONObj);
//Format Data for POST
var POSTData = JSON.stringify(JSONObj);
newXHR.send(POSTData);
}
function RequestDone(req){
var res = JSON.parse(req.target.response); console.log(res)
if(res.status=="OK"){alert("Succesfully Sent & Retrieved Data :\n"+res.data.toString())}
else if(res.status=="ERROR"){alert("The server received unexpected data or is missing important parameters")}
else{alert("Unexcpected Error!")}
}
</script>
</body></html>

Reset table preferences with angular js

I have the following table in my application where user can set their notification preferences.
when the page loads the $ctrl.getNotificationSettings() will be invoked and it will list the users notification preferences for various categories.please refer screenshot
I have also written a $ctrl.save() which allows the user to update their preferences and save it which works fine.
Now i have a reset button with $ctrl.cancelSettings().here i want the user to be able to change few preferences and if he decides to revert it before saving it the table should be set with the preferences how it was when loaded. Need some help on this part.
i cannot use forms here because of some other challenges.
HTML
<tbody>
<tr data-ng-repeat="app in $ctrl.notificationSettings" class="content-box">
<td data-ng-bind="app.appName"></td>
<td><ng-checkbox data-checked="app.email" rounded="true"></ng-checkbox></td>
<td><ng-checkbox data-checked="app.sms" rounded="true"></ng-checkbox></td>
</tr>
</tbody>
</table>
<div class="content-box">
<button class="ng-button-primary" data-ng-click="$ctrl.saveSettings()">Save</button>
<button class="ng-button-secondary" data-ng-click="$ctrl.cancelSettings()">Reset</button>
</div>
JS
$ctrl.getNotificationSettings = function () {
var url = "http://localhost:3000/json/notification-settings.json";
rsicontext.getData(url).then(function (response) {
$ctrl.notificationSettings = response.data;
$ctrl.appName = response.data.appName;
$ctrl.emailNotification = response.data.email;
$ctrl.smsNotification = response.data.sms;
});
};
$ctrl.cancelSettings = function () {
console.log("cancel settings");
};
JSON format to list the data
[{
"appName":"Finance",
"email":true,
"sms":false
},
{
"appName":"Sports",
"email":true,
"sms":true
},
{
"appName":"Economics",
"email":false,
"sms":false
},
{
"appName":"Health",
"email":false,
"sms":true
}]
what about the use of angular.copy to make a deep copy of the original object?
$ctrl.getNotificationSettings = function () {
var url = "http://localhost:3000/json/notification-settings.json";
rsicontext.getData(url).then(function (response) {
$ctrl.notificationSettings = response.data;
$ctrl.appName = response.data.appName;
$ctrl.emailNotification = response.data.email;
$ctrl.smsNotification = response.data.sms;
$scope.origData = angular.copy(response.data);
});
};
$ctrl.cancelSettings = function () {
$ctrl.notificationSettings = $scope.origData;
$ctrl.appName = $scope.origData.appName;
$ctrl.emailNotification = $scope.origData.email;
$ctrl.smsNotification = $scope.origData.sms;
};
I think there's 2 ways to solve your problem:
After retrieving data store it in temporary placeholder, and if user executes $ctrl.cancelSettings set form data to that of placeholder.eg:
$ctrl.getNotificationSettings = function () {
var url = "http://localhost:3000/json/notification-settings.json";
rsicontext.getData(url).then(function (response) {
$ctrl.placeholder = {};
$ctrl.notificationSettings = response.data;
$ctrl.placeholder.notificationSettings = response.data;
$ctrl.appName = response.data.appName;
$ctrl.placeholder.appName = response.data.appName;
$ctrl.emailNotification = response.data.email;
$ctrl.placeholder.emailNotification = response.data.email;
$ctrl.smsNotification = response.data.sms;
$ctrl.placeholder.smsNotification = response.data.sms;
});
};
$ctrl.cancelSettings = function () {
$ctrl.notificationSettings = $ctrl.placeholder.notificationSettings;
$ctrl.appName = $ctrl.placeholder.appName;
$ctrl.emailNotification = $ctrl.placeholder.emailNotification;
$ctrl.smsNotification = $ctrl.placeholder.smsNotification;
};
Or another solution would be just repeat the first function call in cancel operation:
$ctrl.cancelSettings = function () {
var url = "http://localhost:3000/json/notification-settings.json";
rsicontext.getData(url).then(function (response) {
$ctrl.notificationSettings = response.data;
$ctrl.appName = response.data.appName;
$ctrl.emailNotification = response.data.email;
$ctrl.smsNotification = response.data.sms;
});
};

node js db.get is not a function

I am having this error I can't figure out how to fix;
TypeError: db.get is not a function
routes\boxes.js:20:25
server.js:45:5
database.js
module.exports = {
'url' : 'mongodb://localhost/database'
};
server.js
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var db = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(db.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'secretkeykeykeykey' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes/routes')(app, passport); // load our routes and pass in our app and fully configured passport
var boxes = require('./app/routes/boxes');
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/portal', boxes);
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
boxlist.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoxlistSchema = new Schema({
name: {
type: String
},
//insert your other key of collection
});
module.exports = mongoose.model('Boxlist', BoxlistSchema);
boxes.js
var express = require('express');
var router = express.Router();
var collection = require('./boxlist');
/*
* GET boxlist.
*/
router.get('/boxlist', function(req, res) {
var db = req.db;
var collection = db.get('boxlist');
collection.find({},{},function(e,docs){
res.json(docs);
});
});
/*
* POST to addbox.
*/
router.post('/addbox', function(req, res) {
var db = req.db;
// var collection = db.get('boxlist');
db.collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
/*
* DELETE to deletebox.
*/
router.delete('/deletebox/:id', function(req, res) {
var db = req.db;
var collection = db.get('boxlist');
var boxToDelete = req.params.id;
collection.remove({ '_id' : boxToDelete }, function(err) {
res.send((err === null) ? { msg: '' } : { msg:'error: ' + err });
});
});
module.exports = router;
global.js
// Boxlist data array for filling in info box
var boxListData = [];
// DOM Ready =============================================================
$(document).ready(function () {
// Populate the box table on initial page load
populateTable();
// Boxname link click
$('#boxList table tbody').on('click', 'td a.linkshowbox', showBoxInfo);
// Add Box button click
$('#btnAddBox').on('click', addBox);
// Delete Box link click
$('#boxList table tbody').on('click', 'td a.linkdeletebox', deleteBox);
});
// Functions =============================================================
// Fill table with data
function populateTable() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON('/portal/boxlist', function (data) {
// Stick our box data array into a boxlist variable in the global object
boxListData = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function () {
tableContent += '<tr>';
tableContent += '<td>' + this.boxname + '</td>';
tableContent += '<td>' + this.vm + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#boxList table tbody').html(tableContent);
});
};
// Show Box Info
function showBoxInfo(event) {
// Prevent Link from Firing
event.preventDefault();
// Retrieve boxname from link rel attribute
var thisBoxName = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = boxListData.map(function (arrayItem) {
return arrayItem.boxname;
}).indexOf(thisBoxName);
// Get our Box Object
var thisBoxObject = boxListData[arrayPosition];
//Populate Info Box
$('#boxInfoName').text(thisBoxObject.fullname);
$('#boxInfoVm').text(thisBoxObject.vm);
$('#boxInfoDescription').text(thisBoxObject.description);
$('#boxInfoVersion').text(thisBoxObject.version);
};
// Add Box
function addBox(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addBox input').each(function (index, val) {
if ($(this).val() === '') {
errorCount++;
}
});
// Check and make sure errorCount's still at zero
if (errorCount === 0) {
// If it is, compile all box info into one object
var newBox = {
'boxname': $('#addBox fieldset input#inputBoxName').val(),
'init': $('#addBox fieldset input#inputBoxInit').val(),
'vm': $('#addBox fieldset input#inputBoxVm').val(),
'description': $('#addBox fieldset input#inputBoxDescription').val(),
'version': $('#addBox fieldset input#inputBoxVersion').val()
}
// Use AJAX to post the object to our addbox service
$.ajax({
type: 'POST',
data: newBox,
url: '/portal/addbox',
dataType: 'JSON'
}).done(function (response) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addBox fieldset input').val('');
// Update the table
populateTable();
} else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
} else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
// Delete Box
function deleteBox(event) {
event.preventDefault();
// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this box?');
// Check and make sure the box confirmed
if (confirmation === true) {
// If they did, do our delete
$.ajax({
type: 'DELETE',
url: '/portal/deletebox/' + $(this).attr('rel')
}).done(function (response) {
// Check for a successful (blank) response
if (response.msg === '') {} else {
alert('Error: ' + response.msg);
}
// Update the table
populateTable();
});
} else {
// If they said no to the confirm, do nothing
return false;
}
};
portal.js
<!-- views/profile.ejs -->
<!doctype html>
<html>
<head>
<title>Vagrant CLI Node API</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<style>
body {
padding-top: 80px;
word-wrap: break-word;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/global.js"></script>
</head>
<body>
<div class="container">
<div class="page-header text-center">
<h1><span class="fa fa-th"></span> Portal</h1>
Profile
Logout
</div>
<div class="row">
<!-- AVAILABLE BOXES -->
<div class="col-sm-6">
<div id="boxList" class="well">
<h3><span class="fa fa-th"></span> Available Boxes</h3>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Vm</th>
<th>Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<!-- BOX INFO -->
<div class="col-sm-6">
<div class="well" id="boxInfo">
<h3><span class="fa fa-th"></span> Box info</h3>
<p>
<strong>Select box name for more information</strong>
<br>
</p>
<p><strong>Name:</strong> <span id='boxInfoName'></span>
<br/><strong>Vm:</strong> <span id='boxInfoVm'></span>
<br/><strong>Description:</strong> <span id='boxInfoDescription'></span>
<br/><strong>Version:</strong> <span id='boxInfoVersion'></span></p>
<a class="fa fa-plus" href="#">
<i></i> start box instance and add to account</a>
</div>
</div>
<!-- ADD NEW BOX -->
<div class="col-sm-6">
<div class="well">
<h3><span class="fa fa-th"></span> Add box</h3>
<p>
<strong>Add new box to `available boxes`</strong>
<br>
</p>
<form id="addBox" class="form-inline" action="/portal/addbox" method="post">
<fieldset class="form-group">
<input id="inputBoxName" type="text" class="form-control" placeholder="Boxname" />
<input id="inputBoxInit" type="text" class="form-control" placeholder="Init" />
<input id="inputBoxVm" type="text" class="form-control" placeholder="Vm" />
<input id="inputBoxVersion" type="text" class="form-control" placeholder="Description" />
<input id="inputBoxDescription" type="text" class="form-control" placeholder="Version" />
<br>
<br>
<button type="submit" id="btnAddBox" class="btn btn-primary">Add Box</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Does anybody know what's going on and how to fix this? My code excludes node_modules link to dropbox
Thanks
PS. Parts of these codes are from this tutorial: link which can be forked from GitHub: link. This code works, but I've implemented it into my own application and as far as I know it's now the same code, but I get the error in my app, but not in his app.
Do one thing, remove db.get('boxlist');
Make a new file with the name boxlist
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoxlistSchema = new Schema({
name: {
type: String
},
//insert your other key of collection
});
module.exports = mongoose.model('Boxlist', BoxlistSchema);
In your boxes.js add
var collection = require('/boxlist');
now you can directly use queries,need not use var collection = db.get('boxlist');
Just delete this line from the code.
You have to define port number for accessing database.
Eg:
mongodb://localhost:27017/database
To fetch collection follow documentation https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
var collection = db.collection('test');

Categories