CORS-Error / using hosted file with datatables? - node.js

i want to read this txt-file using datatables.net
https://www.rapidtech1898.com/aaadownload/arrays.txt
But when i want to use the file with the following files the output is not working i have this error in the chrome inspector:
(datatables is not reading as it sould and the inspector shows me that)
(at first i had the txt-file locally and read that there are some problems with that using chrome with local file - but this is a "normal" http-link isn´t it? - why is this stil not working as expected?
I also tried to do the same thing locally before - but i get the same error:
I have an index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container py-5">
<header class="text-center text-white">
<h1 class="display-4">Levermann Scores</h1>
</header>
<div class="row py-5">
<div class="col-lg-10 mx-auto">
<div class="card rounded shadow border-0">
<div class="card-body p-5 bg-white rounded">
<div class="table-responsive">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="mainAJAX.js"></script>
</body>
</html>
And this is the mainAJAX.js file:
$(document).ready(function() {
$('#example').DataTable( {
// "ajax": "http://localhost:2121/arrays.txt"
"ajax": "https://www.rapidtech1898.com/aaadownload/arrays.txt"
} );
} );
Somebody told me - that if also the server is hosted on the same domain (like rapidtech1898.com) it would probably work. But is there no way to test such think locally before deploying this somewhere else?

For reasons of security, that is how CORS works. You cannot request data from a different origin unless the server allows it. However, for the purpose of development, you can disable CORS in multiple ways. There is a nice article for it here. But my personal favourite is this solution (to use a proxy that doesn't bypasses CORS):
fetch('https://cors-anywhere.herokuapp.com/https://www.rapidtech1898.com/aaadownload/arrays.txt', {
method: "GET",
headers: {
"Content-type": "application/json;charset=UTF-8",
"x-requested-with": "localhost:3000"
}
}).then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log(err));

I think i found the problem -
In the server-js i have to usse express.static for the data-folder:
const express = require("express");
const app = express();
app.use(express.static('data'))
app.listen(2121, () => {
console.log("Server is running on port 2121...");
});
And in the datafolder i have to put all files (index.html, mainAJAX.js and arrays.txt).
Then i can call the text-file in the mainAJAX.js like that:
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "arrays.txt"
} );
} );

Related

When I use create function of Monaco Editor, it comes out "contextKeyService.ts:393 Element already has context attribute"

HTML
<script type="text/javascript" src="/static/opt/require.js" data-main="/static/opt/demo"></script>
<script type="text/javascript" src="/static/opt/demo.js"></script>
<script src="/static/opt/monaco-editor/package/min/vs/loader.js"></script>
<div class="col-md-12 col-sm-12 col-xs-12" style="margin-top: 20px">
<div class="col-md-4 col-sm-4 col-xs-4" style="padding: 0;display: inline-flex;margin-left: 175px">
<div id="input_editor" ></div>
</div>
<div class="col-md-4 col-sm-4 col-xs-4" style="margin-left:165px;display: inline-flex">
<div id="show_editor" ></div>
</div>
</div>
demo.js
require.config({paths:{'vs':'/static/opt/monaco-editor/package/min/vs'}});
$(document).ready(function () {
require(['vs/editor/editor.main'], function(){
var input_editor = monaco.editor.create(document.getElementById("input_editor"), {
value: "aaa"
})
})
require(['vs/editor/editor.main'], function(){
var show_editor = monaco.editor.create(document.getElementById("show_editor"), {
value: "bbbbb"
})
})
})
Is there anything wrong in my code? How should I use monaco editor in HTML?
And is there any api to color somelines red or green in the Monaca Editor?
Thanks

Cannot read property 'price' of undefined in VueJs Application

I am creating shopping cart system by using vueJs. I want to display the list of item that user want to by but when I run the application and try to add product in checkout list ,I am getting following errors in google chrome console windows when I want to add the item into list.
[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"
(found in <Root>)
warn # vue.js:634
vue.js:1897 TypeError: Cannot read property 'name' of undefined
at eval (eval at createFunction (vue.js:11628), <anonymous>:3:265)
at Proxy.renderList (vue.js:2658)
at Proxy.eval (eval at createFunction (vue.js:11628), <anonymous>:3:183)
at Vue._render (vue.js:3545)
at Vue.updateComponent (vue.js:4061)
at Watcher.get (vue.js:4472)
at Watcher.run (vue.js:4547)
at flushSchedulerQueue (vue.js:4305)
at Array.<anonymous> (vue.js:1989)
at flushCallbacks (vue.js:1915)
logError # vue.js:1897
cart.html:91 Uncaught (in promise) TypeError: Cannot read property 'price' of undefined
at cart.html:91
Here is my cart.html code .
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="bootstap.css">
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>-->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>-->
<!--<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js">
</script>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="index.html">Shop</a>
</li>
<li class="nav-item">
<a class="nav-link" href="index.html">Show All Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/AddProducts.html">Add Product</a>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.html"> cart</a>
</li>
</ul>
</nav>
<br />
<div class="container" id="app">
<h2>Your cart</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>quantity</th>
<th>Rate</th>
<th>vendor</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr v-for="cartItem in cartItems">
<td>{{cartItem.product.name}}</td>
<td>
<button type="button" class="btn btn-primary" v-on:click="changequantity(cartItem.productId,-1)">-</button>
{{cartItem.quantity}}
<button type="button" class="btn btn-primary" v-on:click="changequantity(cartItem.productId,+1)">+</button>
</td>
<td>{{cartItem.product.price}}</td>
<td>{{cartItem.product.vendor.name}}</td>
<td>{{cartItem.quantity*cartItem.product.price}}</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><b>Total</b></td>
<td>{{this.totalPrice}}</td>
</tr>
</tbody>
</table>
</div>
<script>let app = new Vue({
el: "#app",
data: {
totalPrice: 0,
price: 0,
cartItems:[]
},
methods:{
fetAllcartItems(){
new Promise((resolve)=>{
axios.get('/api/cart').then(function (response) {
resolve(response.data)
})
}).then((data)=>{
console.log(data)
this.cartItems=data
// console.log(data)
for(d in data){
this.totalPrice = this.totalPrice+ (d.quantity )* (d.product.price);
}
// console.log(this.products)
})
},
changequantity(id,quantity){
var obj = {id : id , quantity: quantity}
// let iddd = parseInt(id)
console.log(this.cartItems)
let index =this.cartItems.findIndex(item => item.productId == id)
this.totalPrice = this.totalPrice + this.cartItems[index].product.price * quantity
if(this.cartItems[index].quantity ===1 && quantity===-1){
this.cartItems.splice(index ,1);
}
new Promise((resolve)=>{
axios.post('/api/cart/add',obj).then(function (response) {
resolve(response.data)
})
}).then((data)=>{
console.log(data)
if(data.quantity>0)
this.cartItems[index].quantity = data.quantity
/*for(d of data){
this.totalPrice = this.totalPrice+ (d.quantity )* (d.product.price);
}*/
})
// location.reload();
}
}
})
app.fetAllcartItems();</script>
</body>
</html>
Here is the screen shot when I clicked the buy button.
Here is the screen shot when I run the applications..
To see why name is showing you need to check which data you are getting, check it on VueDevtool or else make put console.log(this.cartItems) on a proper place and see how its related , make sure that in this object cartItems is an array of object where poduct is also object and name has value/null.
Also for(d in data) , replace with for(let d in data)
for(d in data){ seems almost certainly wrong. Perhaps you meant for(const d of data) {? In its original form d is a string key, not the item in the array. That's plausibly the cause of the second error, the one about price.
For the error about name I would guess it's this:
<td>{{cartItem.product.vendor.name}}</td>
It looks like cartItem.product.vendor is undefined in some cases.
I strongly suggest you start using a linter. Your code is full of other small defects that I would expect a linter to pick up for you.
For starters, you shouldn't be creating all those new promises.

Can not convert Html content to Pdf

Hi i am trying to convert html contents to pdf files using JsPDF but it is convert the pdf file. But the file contains empty pdf file. There is no content to displayed like header image and date. Could any body advice to me what is the problem?
$("#btn-add").on('click', function () {
var hDate ="Test";
$('#heDate').html(hDate);
var pdf = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
pdf.fromHTML($('#cover').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
pdf.save('sample-file.pdf');
}
});
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="../Scripts/CoverLetter.js"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/jspdf/1.2.61/jspdf.min.js"></script>
<script type="text/javascript" src="../Scripts/html2canvas.js"></script>
<div id="cover" class="formarea">
<table>
<tr>
<td><img src="../Images/Header.png" /></td>
</tr>
<tr>
<td>
<div>
<label> Date: </label>
<label id="heDate"> </label>
</div>
<div id="editor"></div>
</td>
</tr>
</table>
</div>
<table>
<tr>
<td>
<button type="button" id="btn-add" class="btn">Create Letter</button>
</td>
</tr>
</table>
My test code which works in my local.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<script type="text/javascript">
$(function () {
$("#btn-add").on('click', function () {
var hDate = "Test";
$('#heDate').html(hDate);
var pdf = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
pdf.fromHTML($('#cover')[0], 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
},
function (dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('Test.pdf');
});
});
})
</script>
</head>
<body>
<div id="cover" class="formarea">
<table>
<tr>
<td><img src="../Images/Header.png" /></td>
</tr>
<tr>
<td>
<div>
<label> Date: </label>
<label id="heDate"> </label>
</div>
<div id="editor"></div>
</td>
</tr>
</table>
</div>
<table>
<tr>
<td>
<button type="button" id="btn-add" class="btn">Create Letter</button>
</td>
</tr>
</table>
</body>
</html>

vaadin-grid not visible within a paper-header-panel

I am trying to display a table data using vaadin-grid, embedded within a paper-header-panel element. The data is supposed to come from a Rest call. The Rest client used is and I am binding the last-response attribute with the 'items' attribute of the vaadin-grid. When I am inspecting the HTML using firebug, I am able to see the table is properly getting created, but in the frontend nothing is getting visible.
Below is my custom element: 'aws-api-gateway-call'
<template>
<iron-ajax
auto
url="{{url}}"
handle-as="json"
last-response="{{handleResponse}}">
</iron-ajax>
<vaadin-grid items="{{handleResponse}}" selection-mode="multi">
<table>
<colgroup>
<col name="fileName">
<col name="titleName">
<col name="artist">
<col name="albumName">
<col name="action">
</colgroup>
<thead>
<tr>
<th style="z-index: 10">MP3 File Name</th>
<th>Title Name</th>
<th>Artist Name</th>
<th>Album Name</th>
<th>Action</th>
</tr>
</thead>
</table>
</vaadin-grid>
</template>
<script>
Polymer({
is: "aws-api-gateway-call",
properties : {
hostname:{
value: 'test',
notify: true
},
stage:{
value: 'test',
notify: true
},
method:{
value: 'test',
notify: true
},
url:{
computed: 'computeUrl(hostname, stage, method)'
}
},
computeUrl: function(hostname, stage, method){
console.log('URL to call-->' + [hostname, stage, method].join('/'))
return [hostname, stage, method].join('/')
}
});
</script>
And, here is my :
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>An Web-app to customize MP3 songs' metadata</title>
<link rel="shortcut icon" href="img/vector-black-ipod-10170961.jpg" />
<script type="text/javascript" src="bower_components/webcomponentsjs/webcomponents.js"></script>
<script type="text/javascript" src="bower_components/prefixfree/prefixfree.js"></script>
<link rel="import" href="bower_components/paper-header-panel/paper-header-panel.html">
<link rel="import" href="bower_components/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="elements/api_calls.html">
<link rel="stylesheet" href="css/main.css">
</head>
<body class="fullbleed layout vertical">
<paper-header-panel class="flex">
<div class="paper-header ipodHeaderPanel">My Ipod Customizer Application</div>
<div class="content">
<aws-api-gateway-call
hostname="https://<acct-id>.execute-api.us-west-2.amazonaws.com"
stage="mp3file"
method="MP3MetadataReadMicroService">
</aws-api-gateway-call>
</div>
</paper-header-panel>
</body>
</html>
Can you please help me understand the issue? And how to fix it?
I had the same problem with paper-scroll-header-panel and vaadin-grid. I found two causes/solutions for this:
A quick inspect revealed the page-scroll-header-panel had a height of 0px. Making sure that the pager-scroll-header-panel height was 100% fixed it:
.max-height {
height: 100%;
}
<paper-scroll-header-panel fixed class="max-height">
</paper-scroll-header-panel>
The paper-scroll-header-panel will create a mainContainer div and height: with position:'absolute' to place it's contents (which vaadin-grid might not like).
If the height is not your problem then try to override the position of the mainContainer to 'relative' to diagnose:
#mainContainer.paper-scroll-header-panel {
position: relative !important;
}
Disclaimer: Try to stay away from the !important clause, it usually causes huge negative impact on the style sheet’s maintainability. Inspect the mainContainer closely first since height:0 is usually the cause for this kind of things.
Hope this helps!

How does routing affect form validation

I'm working on my first project in node and I'm trying to validate the a form using jQuery validation http://jqueryvalidation.org
I have it working on jsfiddle http://jsfiddle.net/o16u2fLq/ , but in my project my form is submitting without the validations. I think it has to do with how I'm routing the form, but I'm not sure what the problem is.
Here are my routes:
var express = require('express');
var router = express.Router();
var Greeting = require('../models/greetings');
router.get('/', function(req, res) {
Greeting.getGreetings(req).then(function (greetings) {
res.render('index', { greetings: greetings });
res.redirect('/');
});
});
router.post('/greeting', function(req, res){
console.log(req.body);
Greeting.createGreeting(req, res);
res.redirect('/');
Greeting.getGreetings(req).then(function (greetings) {
res.render('index', { greetings: greetings });
});
});
module.exports = router;
I've tried playing around with the routes, but nothing was working. How am I able to validate the form before posting the submission?
Edit:
html as requested
<!DOCTYPE html>
<html>
<head>
<link href="./bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="./bower_components/jquery-ui/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="./css/custom.css">
</head>
<body>
<div class="container-fluid" style="padding-top:20px">
<form action="/greeting" method="Post" enctype="application/x-www-form-urlencoded" class="form-horizontal col-lg-4" id="welcome">
<div class="form-group">
<label for="guest" class="col-lg-3 control-label">Guest Name: </label>
<div class="col-lg-9">
<input type="text" class="form-control" id="guest" name="guest">
</div>
</div>
<div class="form-group">
<label for="message" class="col-lg-3 control-label">Message: </label>
<div class="col-lg-9">
<textarea class="form-control" id="message" name="message" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<label for="datepicker" class="col-lg-3 control-label">Date: </label>
<div class="col-lg-9">
<input type="text" class="form-control" name="display_date" id="datepicker">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-3 col-lg-9">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<div class="col-lg-offset-2 col-lg-5">
<table class="table">
<thead>
<th>
Guest
</th>
<th>
Message
</th>
</thead>
<tbody>
<% for(var i=0; i < greetings.length; i++) { %>
<tr>
<td><%= greetings[i].guest %></td>
<td><%= greetings[i].message %></td>
</tr>
<% } %>
</tbody>
</table>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="./bower_components/jquery-ui/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
<script src="./scripts/custom.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</html>
in my openion
create a validator.js file
add all validations
in app.js file first you point to the valdator, after go to router folder

Resources