Node.js post data that isn't a form - javascript

I have a folder icon, which when a user clicks on, I want to be able to find out what folder it in my node.js server.
HTML:
<header>
<script>
function newfile(filecode){
console.log(filecode)
$.post('/Y9computing', filecode).done()
}
</script>
</header>
<body>
<div class="folderIcon" onclick="newfile('Y9UNIT1')"></div>
</body>
node.js:
app.post('/Y9computing', function (req, res) {
console.log("FIRED!")
console.log(req.filecode) //don't know what to put in here
At the moment, the server logs "FIRED!" and then "undefined", I also think I'll have to respond from the server with something.

Related

How to get elements from another HTML file

I'm trying to make a node.js application that takes the input from a text box in an HTML file. I want to store this value in an array, although I'm not sure how. My overall goal is to make a chat application and I assume there is some easier way to get the input without having to reference an HTML file.
Also, are there any templates for an html file because I'm not very skilled enough with HTML to make a decent-looking webpage. So if there is some template I could use, everything would look better.
My code:
var events = require('events');
var express = require('express');
var http = require('http');
var app = express();
var msg = [];
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.read('/', function() {
});
app.listen(3000, function() {
console.log("Server is running on port " + 3000);
});
#firstHead {
font-family: Georgia, 'Times New Roman', Times, serif;
}
<header>
<h1 id='firstHead'>
This is a header!
</h1>
</header>
<body>
<input type="text" id="inText" placeholder="Enter text here" />
</body>
Help appreciated!
First of all, your HTML code has so many mistakes. This the correct version of your code (You won't be using it, it's just to give you an idea of what mistakes you've done):
<!DOCTYPE html>
<html>
<head>
<style>
#firstHead {
font-family: Georgia, 'Times New Roman', Times, serif;
}
</style>
</head>
<body>
<h1 id='firstHead'>
This is a header!
</h1>
<form id="msg" method="GET" action="/msg">
<input type="text" name="msgContent" id="inText" placeholder="Enter text here" />
<input type="submit" value="Send">
</form>
</body>
</html>
Now this HTML page will send input contents to localhost:3000/msg as a POST request See here for more details, the problem here is that page will be refreshed or redirected (depending on your implementation, you should in this case use AJAX if you want SPA). Even if you used AJAX it will be hard for you to implement a chat application using HTTP requests. It would be a better idea to use WebSocket protocol to achieve this functionality. There's a module called Socket.io that will help you a lot. It has an event-driven system as it's great for real-time applications, you can check their official website; they've have an example of a chat application written in few hundred lines of code.
Now let's move to your server-side code, firstly .. there's no method of express called read, here's a working version of your code:
var express = require('express');
var http = require('http');
var app = express();
var msg = [];
app.get('/', function(req, res){
//You should use some template engines like EJS or Pug to render your HTML page with messages or the user will see nothing
res.sendFile(__dirname + '/index.html');
});
app.get('/msg', function(){
msg.push(req.query.msgContent);
res.redirect("/");
});
app.listen(3000, function(){
console.log("Server is running on port " + 3000);
});
The above code will work as it should but you'll see nothing in the client-side cuz you didn't render (or send msg array to client-side script to embed it). I'm just trying to make things clear to you not give you an implementation of your idea
I hope this helped you a little.

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>

Automate Log In on Website (Autofill and Submit)

I am trying to visit a website and log in automatically.
After this, I want to return whether or not this was a success or failure, but I can't get it to work. The page loads blank and nothing happens.
Note: I have deliberately greyed out the URL.
Below is my attempt,
<HTML>
<HEAD>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
<TITLE>Login</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
<script type="text/javascript">
$(document).ready(function () {
runLogin();
});
function runLogin(){
alert("start");
if (window.location.indexOf("url") > -1) {
jQuery("#j_username").val("username");
jQuery("#j_password").val("password");
jQuery("#loginForm").submit();
}
}
</script>
If you want to test your login form, use Protractor or other e2e test framework, but this way does not seem very safe.
http://angular.github.io/protractor/
It's loading a blank page because your back-end script isn't redirecting back to the page you started on. One option is to send the current webpage URL as an extra field to the login form so that it can redirect back after it has logged in. This will require you to refactor your back-end code so that it can handle this extra information (not really possible if you're using j_security_check). Another option is to make an AJAX request to your login page so that it doesn't actually redirect the page, it just submits the form quietly and then JS handles the response.
If you want to add the URL of the current page to the login request, do this:
function runLogin() {
if (window.location.indexOf("url") > -1) {
jQuery("#j_username").val("username");
jQuery("#j_password").val("password");
jQuery("#loginForm").append(
'<input type="hidden" name="url" value="'+window.location.href+'"/>'
);
jQuery("#loginForm").submit();
}
}
If you want to use AJAX to send a login request:
function runLogin() {
var $form = $("#loginForm");
$.post($form.attr("action"), $form.serialize(), function(data) {
// login successful/unsuccessful message displays
// depending on what "data" contains
});
}

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

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
}});

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.

Categories

Resources