client request for get http://localhost:3000/test.s - javascript

I am creating my website using MEAN stack. on server NodeJs is running which has a route /test and is connected to DB. on the cleint side in Angularjs my client.ejs template include a script like
which is used in the controller in the page body.Now if i click on some page which hit the route /test and Nodejs renders load client.ejs. i can see an error " 500 internal error" for Get request http://localhost:3000/test.js
Why? it is happening like this?
nodejs code:
app.post("/test",function(req,res))
{
/do some stuff with req
res.status(200);
res.render("public/hello");
}
hello.ejs:
<html>
<head>
<script scr="test.js"></script>
</head>
<body ng-app="my-app">
<div ng-controller="my-controller">
<form ng-submit="dosction()">
<input type=text>
<input type=submit>
</form>
</div>
</head>
<html>
test.js
angular.module("my-app",[]).controller("my-controller", function($scope){
dosaction=function()
{
//some stuff
}});

Related

Http Json Post Response js

I have written a demo app at eclipse and I have a MySQL database.
I'm using hibernate to retrieve data from the database and now I want to
show up them to a browser.
I have a UserLogin class which is a servlet; the class waits for a HttpRequest and then the hibernate is being enable to bring me back the result set of the database.
By far, it works well; I have check my server side component using Postman and I do get a response as expected from my class, UserLogin.
My challenge is that I'm not really familiar with front-end.
I have the example below, using JavaScript with HTML in order to make a HTTP request.
I have check from my chrome browser's console and got the response below:
{"response":"ok","FileSystem":"Internal","userID":1}
but I need to be able to manipulate it (the response above) so as to display it on the page.
How can I achieve that?
<!DOCTYPE html>
<html>
<head>
<title>UserLogin</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<p><input id="username" type="text" name="username" placeholder="username"></p>
<p><input id="password" type="password" name="password" placeholder="password"></p>
<button onclick="return login()">Submit</button>
<script>
function login() {
const params = {
username: document.querySelector('#username').value,
password: document.querySelector('#password').value
}
const http = new XMLHttpRequest()
http.open('POST', 'http://127.0.0.1:8080/.../UserLogin', true)
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=utf-8;')
http.send(JSON.stringify(params)) // Make sure to stringify
http.onload = function() {
console.log(http.responseText)
}
}
</script>
</div>
</body>
</html>

How to call a function from index.html to app.js file in node js application javascript

I had a node js application where I have my app.js and one html which gets displayed for the route /index.Now In my index file I had a button and text box and when I click button Iam trying to call a function.Where in that function I will have a variable with some text "Hello" which should be displayed in text box.I couldnt achieve this can some one help.
<html>
<body>
<div class="jumbotron" style="padding:40px;">
<h1>Hello!!!</h1>
<div>
<button type="submit" onclick="getData();">Call</button>
<input type="text">
</div>
</div>
</div>
</body>
</html>
app.js
app.get('/index',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
function getData(){
console.log("Hello");
var text="Hello";
};
Right now Im getting reference error that getData is not defined.Can someone help over here.
I think you may have misunderstood what NodeJS is. Node isn't like other JavaScript or jQuery that runs in the browser.
Node is code that runs on the server. What you've correctly done in your app.js is have the server send the index.html file to the browser. But after that point all that the browser knows about and has access to is the index.html file, it is a separate file and context and so has no access to the server anymore.
The only way to have your page call a function on the server would be to create some sort of API where your page sends a separate http request to the server, which then responds with the function's output.
index.html runs in browser so you can't call getData() function that is defined on server side in app.js
Move getData() function body to index.html as Nenad Vracar suggests or use some kind of API for client-server communication.
code moved to index.html
<html>
<body>
<script>
function getData() {
var text="Hello";
document.querySelector('#input_id').value = text;
}
</script>
<div class="jumbotron" style="padding:40px;">
<h1>Hello!!!</h1>
<div>
<button type="submit" onclick="getData();">Call</button>
<input type="text" id="input_id">
</div>
</div>
</div>
</body>
</html>

How to load local text information into <div> section

I am trying to draw a diagram by using below codes.
It works well.
As you can see, I should put some text information in the div.
If there is a sample.txt which includes this information in local drive, can I load it into div section dynamically instead of putting it manually?
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sample Diagram</title>
</head>
<body>
<div class="diagram">
Title: Diagram
<!-- Participant FIRST
Participant SECOND
Participant D
Participant F
Participant G //-->
E->F: 2
SECOND->FIRST: 1
FIRST->SECOND: 1
C-->SECOND: Request token
C->E: 2
SECOND->FIRST: Forward request
FIRST->>C: Send token
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/js-sequence-diagrams/1.0.4/sequence-diagram-min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
UPDATE
/test/index.html
/test/js/index.js
/test/js/sample.txt
/test/sample.txt
index.js
// js-sequence-diagrams by bramp <http://bramp.github.io/js-sequence-diagrams/>
$(".diagram").sequenceDiagram({theme: 'simple'});
$(function(){
$.get("sample.txt", function(data) {
$(".diagram").text(data);
});
});
sample.txt
Title: Diagram
SECOND->FIRST: 1
FIRST->SECOND: 1
C-->SECOND: Request token
C->E: 1
SECOND->FIRST: Forward request
FIRST->>C: Send token
Without inner text
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sample Diagram</title>
</head>
<body>
<div class="diagram">
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/js-sequence-diagrams/1.0.4/sequence-diagram-min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
Add a file-input element to the HTML page:
<input type="file" id="file" onchange="readTxT()"/>
And select sample.txt manually:
function readTxT(){
var reader = new FileReader();
var files=document.getElementById('file').files;
var f = files[0];
reader.onload = function(e) {
var text = reader.result;
$(".diagram").text(text).sequenceDiagram({theme: 'simple'});
}
reader.readAsText(f);
}
The simplest and easy way is to make get request to the server. And for that you have to use jQuery $.get function. Which will make a request for you.
Here is reference to jQuery.get()
USAGE
// make sure the PATH is correct for `sample.txt`
// $.get(your URL to the file, callback function)
$(function(){
$.get("sample.txt", function(data) {
$(".diagram").text(data);
});
});
If the sample.txt is available on the (http) server the site is hosted with (may be localhost), yes.
Assuming your directory structure is like this (/var/www/ is the server's root directory in my example):
/var/www/
index.html (The file without the diagram content)
sample.txt
js/
index.js
Place this in your index.js:
window.onload = function() {
$.get("sample.txt", function(data) {
$(".diagram").text(data).sequenceDiagram({theme: 'simple'});
});
}
If you're not using any HTTP server, you can't load files from the file system directly - that's part of the Javascript sandbox (security concept).
I would then recommend using something like in lx1412's answer, a manual file chooser is the only way how this could work then.
I've tested the script above using Firefox and an HTTP server; and my edit of lx1412's answer using Firefox without an HTTP server.

Integrating Javascript Libraries with Google App Engine

Just starting to learn web programming (taking class CS 253 on Udacity).
My question is how does integrating JS and google app engine work? I know this is may be a fundamental question about web programming, but I really need some guidance on how to understand this concept.
I am trying to incorporate the Twitch Javascript API into Google App Engine. Basically, I would like to have a small website where users can login via Twitch and it stores their info into a database. I really do not understand how this is possible, since Twitch only has a Javascript API.
Here is the script that I have that works perfectly for connecting to Twitch (from the examples on their git page):
<html>
<head>
<meta charset="utf-8">
<title>TwitchTV SDK Example App</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ttv-api.s3.amazonaws.com/twitch.min.js"></script>
<script>
window.CLIENT_ID = '';
$(function() {
// Initialize. If we are already logged in, there is no
// need for the connect button
Twitch.init({clientId: CLIENT_ID}, function(error, status) {
if (status.authenticated) {
// we're logged in :)
$('.status input').val('Logged in! Allowed scope: ' + status.scope);
// Show the data for logged-in users
$('.authenticated').removeClass('hidden');
} else {
$('.status input').val('Not Logged in! Better connect with Twitch!');
// Show the twitch connect button
$('.authenticate').removeClass('hidden');
}
});
$('.twitch-connect').click(function() {
Twitch.login({
scope: ['user_read', 'channel_read']
});
})
$('#logout button').click(function() {
Twitch.logout();
// Reload page and reset url hash. You shouldn't
// need to do this.
window.location = window.location.pathname
})
$('#get-name button').click(function() {
Twitch.api({method: 'user'}, function(error, user) {
$('#get-name input').val(user.display_name);
});
})
$('#get-stream-key button').click(function() {
Twitch.api({method: 'channel'}, function(error, channel) {
$('#get-stream-key input').val(channel.stream_key);
});
})
});
</script>
<style type="text/css">
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>TwitchTV SDK Example App</h1>
<div class="status">
Status: <input readonly="readonly" size="60" val="Unknown"/>
</div>
<div class="authenticate hidden">
<img src="http://ttv-api.s3.amazonaws.com/assets/connect_dark.png" class="twitch-connect" href="#" />
</div>
<h2 class="authenticated hidden">Authenticated</h2>
<div class="authenticated hidden">
<div id="logout">
<button>Log Out</button>
</div>
<div id="get-name">
<button>Get TwitchTV Name</button>
<input readonly="readonly" size="50" value="Unknown"/>
</div>
<div id="get-stream-key">
<button>Get TwitchTV Stream Key</button>
<input readonly="readonly" size="50" value="Unknown"/>
</div>
</div>
</body>
</html>
How can I communicate data between this client side javascript and Google App Engine? Thanks!
Very broad question. But in general, regarding your case:
You should set up a receiving end (handler) on your App Engine application. It will handle the requests from your client side JavaScript (Hello, world example)
Second, you will need to actually send the data to the server. I see that you're using jQuery. In order to call the server we've seen in the Hello, world example, you'll write something like this: $.get('/', function(data) {console.log(data);}). This will call the server and print to the console the message you got from the server.

How do I get a SignalR hub connection to work cross-domain?

I am trying to get a super simple hub connection working cross-domain but having no luck. I've read dozens of posts and done everything mentioned but still no success.
My server hub is here
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
My server MapHubs call is here
RouteTable.Routes.MapHubs(new HubConfiguration { EnableCrossDomain = true });
Any my javascript client is here
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-2.0.1.min.js"></script>
<script src="~/Scripts/jquery.signalR-1.1.2.min.js"></script>
<script src="/signalr/hubs"></script>
</head>
<body>
<div class="container">
<input type="text" id="displayname" value="Test" />
<input type="text" id="message" value="I'm here" />
<input type="button" id="sendmessage" value="Send" />
</div>
<script type="text/javascript">
$(function ()
{
$.connection.hub.url = 'http://<my url>/';
var chat = $.connection.chatHub;
alert(chat);
$.connection.hub.start().done(function ()
{
alert("Connection succeeded");
}).fail(function ()
{
alert("Connection failed");
});
});
</script>
</body>
</html>
The problem is that it never reaches the Connection succeeded or failed alerts and the alert(chat) call returns undefined.
I've tried several combinations for the $.connection.hub.url line
$.connection.hub.url = 'http://<My url>';
$.connection.hub.url = 'http://<My url>/';
$.connection.hub.url = 'http://<My url>/signalr';
$.connection.hub.url = 'http://<My url>/signalr/';
The developer console in Chrome and Firebug give me the error
Uncaught Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/hubs'></script>.
On the same domain it works fine. This is really starting to drive me crazy so any help would be appreciated.
Thanks,
Jason
Your server is being hosted cross domain yet you're trying to get the hubs from the current domain. Therefore it's failing to retrieve the hubs file and you don't actually have a proxy to work with (which is why everything is not working).
So you have two options:
Manually create the hubs file and host it on the current domain: http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-javascript-client#manualproxy.
Use the raw hub connection API and do not include the signalr/hubs file at all.
Here's a code snippet of how you can use the raw hub connection API: http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-javascript-client#nogenconnection (second code snippet).

Categories

Resources