Node.js - passing values to other pages - javascript

I'm trying to build a web service using node.js.
In this architecture, curl is used to POST data to the index.js app. The index.js app process the output and then it should pass the output to different pages.
For example, if the ID received is between 100-200 then push the ID to movies.html and so on.
Now I have been able to achieve the processing of POST request using CURL and node.js
I have no idea how to pass the data to other pages.
Here is my index.js code.
var http = require('http');
var qs=require('querystring');
var redis=require('redis').createClient();
console.log('Server Starting Now: ');
var count=0;
http.createServer(function (req, res) {
if(req.method=='POST'){
count=count+1;
var body="";
req.on('data',function(data){
body+=data;
});
req.on('end',function(){
var post=qs.parse(body);
console.log(post);
res.write("Received");
redis.lpush('XMLqueue',JSON.stringify(post));
});
}
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
How do I pass the data from this index.js page to other pages?

Create handlers for other URLs which will respond with the data you want it to.
But actually, you seem to be confused by nodejs and overall http server architecture a lot. I'd suggest you to read any "getting started nodejs" tutorial you find at Google and like to get the basics. Also, search for something like "nodejs express" and reading it will probably help you to get an easy start.

Related

Where to put socket.io server in WebStorm Express template

I am trying to add socket.io into generated express server by WebStorm. Where I am supposted to setup server and run socket.on events? Just put them all inside /bin/www, or its messy and I am supposted to make some controller like index and users page have.
PS: Also I have second fast question. Is dumb idea to have express Web server on same port as Socket.IO websocket server? I see, that all websites using subdomain to connect to socket.io, so they must be using different port.
There isn't a single answer to this. But to get some ideas of nice ways to do it, you could download some trusted examples. For example, MEAN.JS uses socket.io, and it is very structured. You may not need everything in the stack, but it's great for getting inspiration on organization. Best of luck!
I get this post to life again because i was trying to make the same thing.
I tried something and it worked !
I just followed the Socket.io doc and tried to adapt it to this template.
https://socket.io/get-started/chat
Here's what i've wrote in my www.js from the template (didn't changed anything in this file).
/**
* Create HTTP server. (This part was in by default)
*/
let server = http.createServer(app);
/**
* Try Socket io integration (This is what i've done)
*/
let io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log("yeet");
});
and here's my layout.pug
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src='/socket.io/socket.io.js')
body
block content
script.
let socket = io();
Now when I get my page, I get the log.
Hope it can help other people.

Send JSON data from express to html NodeJS

Hello all i'm new with node so here my use case i want to post data to my express app and show it on a html page is that possible with nodeJs ?
Here my code
app.post('/', function(req, res){
res.sendFile(__dirname + '/views/index.html', {data: req.body});
})
There are many tutorials showing how to do that. I would recommend first you understand how HTTP protocol works (The message structure : https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html). Then go dive into node and exchange data through requests and responses. I'd recommend body-parser to arrange the data format between the two sides. Also read the express documentation. Hope it helps.

Running a node.js file from website

I have recently started using the Twilio platform to send SMS to my users. I am perfectly able to run the node.js file from the node terminal with the command:
node twilio.js
Now, my goal is to be able to send those SMS, but from my website. For instance, when the user provides his phone number and presses the "Send sms" button. How can I achieve this? I have been looking this up for a while and I came across Express platform, ajax post requests, http server, etc. But, I can't figure out how to use them. I currently make many ajax requests (POST and GET) on my site, but I'm not able to make a request to a node file.
Thanks in advance,
Here is the twilio.js file:
// Twilio Credentials
var accountSid = 'ACCOUNT SID';
var authToken = 'ACCOUNT TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
client.messages.create({
to: 'TO',
from: 'FROM',
body: 'Message sent from Twilio!',
}, function (err, message) {
console.log(message.sid);
});
Being able to run any arbitrary script on your server from a webpage would be a huge security risk - don't do that. I'm not sure where you're hosting your site, or what technology stack you're running your site on, but since you mentioned Express and Node -- if you're using Express I'd recommend that you setup a route that handles an ajax request. When someone presses 'Send SMS' you send an ajax request to that route, and in the handler that gets invoked you place the Twilio logic.
Here is a very simple way to setup an Express request that calls you node module:
twilio.js:
// Twilio Credentials
var accountSid = 'ACCOUNT SID';
var authToken = 'ACCOUNT TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
function sendSms(callback) {
client.messages.create({
to: 'TO',
from: 'FROM',
body: 'Message sent from Twilio!',
}, callback);
}
// Export this function as a node module so that you can require it elsewhere
module.exports = sendSms;
Here is a good start for Express.
server.js:
var express = require('express');
var app = express();
// Requiring that function that you exported
var twilio = require('/path/to/twilio.js');
// Creating a controller for the get request: localhost:8081/send/sms
app.get('/send/sms', function (req, res) {
twilio(function(err, message) {
if (err) res.send(err);
res.send('Message sent: ' + message);
});
});
// Creating an HTTP server that listens on port 8081 (localhost:8081)
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
Then you can run node server.js, go to your browser and go to the url: localhost:8081/send/sms and your message will be sent :)
I'd make it so the client sends a HTTP POST request to the server, and then the server will send the message on behalf of the client.
Easiest way is to use express. I'm a bit unsure of how you're serving your website from a Node.js app without using express. Do you have a custom solution or only a non-connected from end, or something like heroku or something? In any case, you can create a route that processes posts with the following:
app.post("send_twilio_message_route", function(req,res){
// this receives the post request -- process here
});
^ Note that doesn't actually create the express app. See my link below and they give examples of some of the nitty gritty and syntax.
So the above would be on the server, in your Node.js app. From the front-end client code that runs in the browser, you need to create a post. The easiest way and most likely way to do it is through $.post in Jquery. if you are using Angular there's a slightly different syntax but it's the same idea. You call post, point it to a url, and put in the body data.
Make the body of the post request contain data such the message, phone numbers,
authentication token maybe.
See this to be able to get the body from a post request and some more implementation details of how to set it up:
How to retrieve POST query parameters?
Depending on the nature of what you're doing you might consider having the sms processing stuff run separate from the actual web service. I would create the sms unique stuff as its own module and have a function retrieve the router so that you can mount is onto the app and move it about later. This might be overkill if you're doing something small, but I'm basically encouraging you to at the start put thought into isolating your services of your website, else you will create a mess. That being said, if it's just a small thing and just for you it might not matter. Depends on your needs.
Important: I highly encourage you to think about the malicious user aka me. If you don't add any authentication in the post body (or you could include it in the url but I wouldn't do that although it's equivalent), a malicious client could totally be a jerk and expend all of your twilio resources. So once you get it basic up in running, before deploying it to anything that people will see it, I recommend you add authentication and rate limiting.

Communication between an express node server and its displaying html

Really fast, this question may have already been asked, but I am not totally clear on the terminology and have had no success when searching for a solution.
I am attempting to create a simple web application that can receive get and post requests. Then, I would like to take the information I receive from these requests and use them in a javascript file embedded in html that is displayed. I think it may be more clear with code. This is my app.js:
var express = require('express');
var app = express();
var assert = require('assert');
app.use(express.static('javascript'));
app.get('/', function(req, res) {
res.render('index.jade');
});
app.listen(3000);
I would then like to be able to take information received from a get or post request, specifically in JSON format, and then be able to use it in javascript that I have linked to index.jade. To make matters slightly more confusing in index.jade the only line is:
include map.html
So ideally I would be able to get the information to javascript in that html file.
I want to be able to pretty continuously update map.html using javascript based on frequent get and post commands.
This could be a very simple solution, I am pretty new with web application programming in general, and I have been struggling with this problem. Thanks in advance, and ask if you need any clarification.
I think you need to understand what you are doing. You are creating a web server using node.js. Express framework simplifies that for you. The official documentation of express is pretty great. You should refer that especially this link.
Now, in your application, you need to create endpoints for GET and POST requests. You have already created one endpoint "/" (root location) that loads your home page which is the contents of the file index.jade. A small example is :
app.get('/json', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
});
Jade is a templating engine which resolves to HTML. You should refer its documentation as well. Since as you said, you are not very familiar with these, you could simply use HTML as well.
After this tasks are quite simple. In your javascript, using ajax calls you can access the GET or POST endpoints of your server and do the desired actions.
Hope it helps!
The way I get it you want to be able to call an endpoint (lets assume /awesome) pass some info and then write to a Javascript file that you can then reference in your html.
Something like the below would write a main.js file in your public folder. You can make it write whatever you want.
var fs = require('fs');
fs.writeFile("/public/main.js", "console.log('Hello!')", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
You can then reference /public/main.js in your html.
Check that: Writing files in Node.js
If I misunderstood your intentions, apologies. :)
So you want to reviece continuously data from the server maybe web sockts are an option for you http://socket.io/docs/
This way u will open a stable connection from the client to the server. This is a great way if u want to get updates done by other clients.
If you want to trigger the changes by the client then ajaxs calls(http://www.w3schools.com/ajax/) as hkasera mentioned are the way to go.

Would love some help determining where to start with the Node.JS app file provided with BlueMix

I've been reading tutorials for JS and I've got a good idea of the syntax and methodology, now I'm looking to figure out how to use Node.JS to build an app with BlueMix. I'm pretty fluent with Java, but I'm absolutely new to web programming so I'm pretty lost as to how to start. Forgive my current state of being an absolute beginner, but I'm just really stuck. Here's the file they give you to build off of.
/*eslint-env node*/
//--------------------------------------------------------------------------
// node.js starter application for Bluemix
//--------------------------------------------------------------------------
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
To clarify, I get the general purpose of the code - it's commented pretty well, but I just don't know how to start // test on the BlueMix platform. I tried doing things like adding print statements, but nothing really changes.
To give a little insight on what I'm trying to do: Just create a webpage where a user can input a string and I can post a string in response. I'm just trying to learn BlueMix, so I need to do it on this platform, and in Node JS.
I suggest you to take a look at this tutorial: IBM Bluemix DevOps Services - Develop and deploy a Node.js app. It is useful to get started with DevOps Services (reading your comments it seems that you are using it to deploy from the Web IDE to Bluemix) to get a "Hello World" Node.js Web application on Bluemix. It also shows how to apply some changes and re-push them directly on Bluemix.
Just to answer to your questions, assuming that you have already deployed the starter application (as in your example):
Consider that the starter application uses Express.js, that is an application server framework that helps you to manage the incoming requests. Now let's say that you want to send the string "Hello, World!" in HTTP response when the server receives an HTTP GET request (let's say /printhello). Using express you'll have something like:
app.get('/printhello', function (req, res) {
res.send('Hello, World!');
});
Now you just need to do the HTTP GET /printhello from a web page (for example the index page under the public folder of the starter application). You could for example use an onclick event to send the request to the server. You will see that the server receives it and sends the response to the browser, that will show the string "Hello, World!".
The reason why you can't see the "starting server" log is that console.log prints in the Node.js console, not into the HTTP response, so you can't see that from the client. To see that output you can use cf logs (please refer to this blog post).
Finally, I invite you to take a look at the Bluemix - Node.js SDK documentation, it is really simple and clear.
I hope this can give you some starting points.
Check out https://github.com/IBM-Bluemix/bluemix-hello-node. It provides a pretty good starting place for node. There are somethings you need to code around for Node to work for Bluemix. The biggest is binding to the correct port, the port is given through process.env.PORT. I have pasted a super simple Node.app below (the rest of the code is at the GitHub link above).
var express = require("express"),
app = express();
var port = process.env.PORT || 8080;
app.use(express.static(__dirname + '/public'));
app.get("/hello", function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"})
response.end("Hello World!\n");
});
app.listen(port);

Categories

Resources