Using javascript for back-end with google cloud storage? - javascript

I have read that Javascript can be used for back-end of a website, so like server side scripting. I have seen here that nodejs is accepted by Google cloud storage but using node js which confuses me as I don't know how to use it with a website in a text editor e.g. Brackets.
I have been trying to create a server and use the console to show that someone has connected:
var http = require("http");
var fs = require("fs");
var lemon = 2;
function send404Response(response) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("Error 404");
response.end;
}
function onRequest(request, response) {
if (request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Content-Type": "text/html"});
//sends back a readable stream
fs.createReadStream("./index.html").pipe(response);
} else {
send404Response(response);
}
}
http.createServer(onRequest).listen(8080);
console.log("Server is now running...");
'require' was used before it was defined. var http = require("http"); is the first error and I don't know what to do nor can I find any help except that I'm not supposed to do require for a website.
In review please answer these questions:
how do you use Javascript for server side scripting and some
tutorials would be useful.
how to use nodejs with a website, since its a command line.
what is the issue with the code?
Also which port am I supposed to use when using brackets live update?
Please if there is an issue with the question please leave a comment I have tried to follow the rules.

Related

Need to acces Client IP not the server IP for a weather API

I want to create a server-side app using node.js with express. At the moment I am able to get the json document with the location and temperature but after I used pykite to get it online the application would only get the server location to the one who is accessing it. Here is the code in its current form:
var express = require('express');
var app = express();
var request = require('request');
app.get('/api/weather/current_temperature', function (req, res) {
request('http://api.wunderground.com/api/ebb3e0cf5059cce8/conditions/q/autoip.json', function(error, response, body){
if (!error && response.statusCode==200){
res.setHeader('Content-Type', 'aplication/json');
var result = JSON.parse(body);
res.json({ "location": result.current_observation.observation_location.city,"temperature": result.current_observation.temp_c });
}else{
console.log(error, response.statusCode, body);
}
res.end("")
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('The app is up.');
});
I admit I'm new to this but I wanna learn. I would like some help implementing it in this code, if it's possible, a way to access the user's location and determine the weather at his/her location.
Thank you in advance.
P.S.: I would also like some links into some documentation, don't wanna skip anything.
The URL you are linking to http://api.wunderground.com/api/YOUR_KEY/conditions/q/autoip.json (which doesn't work because you didn't provide your key) has autoip in the name.
That implies that it will return a result from whatever IP address the request came from.
So you have two options:
Don't make the request from NodeJS. Make the request from the browser. (This probably isn't advisable given the use of an API key and might run into Same Origin Policy issues).
Find a different API (possibly one from the same site) that lets you specify what IP address or location to use.

My Server is up but when I try to connect to it I am getting an error [Node.js]

I am following a tutorial on Node.js and I think I have done everything to the letter, I run my server (node web.js) and tried to connect to it but I am getting an error. My code is given below, I saw an answer to a similar question but I avoided the error there, I just don't know whats wrong. Please help!
var http = require("http");
function process_request(req, res) {
var body = 'Thanks for calling!\n';
var content_length = body.length;
res.writeHead(200, {
'Content-Length': content_length,
'Content-Type': 'text/plain'
});
}
var s = http.createServer(process_request);
s.listen(8080);
You need to write the content that you are sending back as a response. Add this after your res.writeHead().
res.write(body);
res.end();
You didn't provide the error, but you could try a
res.send(body);
Instead. Also confirm you're hitting http://localhost:8080/ (assuming it's running on localhost).
You are creating content but not sending to client , using res.end you can do like
res.write("Hello World");
res.end(body)

Using pipe() in Node.js net

I'm having trouble wrapping my head around the pipe function shown in several Node.js examples for the net module.
var net = require('net');
var server = net.createServer(function (socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
Can anyone offer an explanation on how this works and why it's required?
The pipe() function reads data from a readable stream as it becomes available and writes it to a destination writable stream.
The example in the documentation is an echo server, which is a server that sends what it receives. The socket object implements both the readable and writable stream interface, so it is therefore writing any data it receives back to the socket.
This is the equivalent of using the pipe() method using event listeners:
var net = require('net');
net.createServer(function (socket) {
socket.write('Echo server\r\n');
socket.on('data', function(chunk) {
socket.write(chunk);
});
socket.on('end', socket.end);
});
pipe() reads from a readable stream and writes to a writeable stream, much like a Unix pipe. It does all "reasonable" things along the way with errors, end of files, if one side falls behind etc. Your particular example is slightly confusing because the socket is both readable and writeable.
An easier to understand example is in this SO question where you read from an http request and write to an http response.
There are 2 sockets per Server-Client Connection (2 endpoints). Socket binds IP Address:Port Number. The client gets assigned random port numbers, while the server has dedicated port number. This is the basic explanation of how socket works.
Piping is reserved for redirecting a readable stream to a writable stream.
What socket.pipe(socket) does?
It redirects all the data from the readable stream (server) to the writable stream (client). We can tweak this by adding event listeners as #hexacyanide has pointed out.
Consider the following request handler
var server = http.createServer(function(req, res){
console.log('Request for ' + req.url + ' by method ' + req.method);
if(req.method == 'GET'){
var fileurl;
if(req.url == '/')fileurl = '/index.html';
else {
fileurl = req.url;
}
}
var filePath = path.resolve('./public'+fileurl);
var fileExt = path.extname(filePath);
if(fileExt == '.html'){
fs.exists(filePath, function(exists){
if(!exists){
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Error 404' + filePath + 'not found </h1>');
//the end() method sends content of the response to the client
//and signals to the server that the response has been sent
//completely
return;
}
res.writeHead(200, {'Content-Type':'text/html'});
fs.createReadStream(filePath).pipe(res);
})
}
}
The fs.createReadStream method reads the file in the given file path (public/index.html) and pipe() writes it to the response (res) for client's view.

GET request in javascript to NodeJS

I'm trying to do a simple conection (request - response) from the javascript code on a web to a server in Node.js.
I have tried to make the request as follows:
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:4444/', false);
request.send();
if (request.status === 200) {
console.log(request.responseText);
}
Running this code I got an error in FireBug
I have continued searching and I found that this method is only to make GET requests on the same domain. To make cross domain requests we must use other strategies.
I found a jQuery method, and it seems that i'm on the right way:
$.get(
'http://localhost:4444/',
function(data) {
alert("sucess");
//Do anything with "data"
}
);
In this case I get the same response without the error.
It seems it works but the "alert" message is never shown! What happens? What am I doing wrong?
The Node.js server code is:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("Response");
response.end();
}).listen(4444);
So you're running into cross domain issues. You have a few options:
1) since you're using node, use socket.io . It's cross domain compliant.
On the client:
<script src="Full path to were socket IO is held on your server//socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('some_callback', function(data){
// receive data
});
socket.emit('some_other_callback', {'data': value}); //send data
</script>
Server:
var io = require('socket.io').listen(server);
// define interactions with client
io.sockets.on('connection', function(socket){
//send data to client
socket.emit('some_callback', {'data': value});
//recieve client data
socket.on('some_other_callback', function(data){
//do something
});
});
2) Since you just want to use GET you can use JSONP
$.getJSON('url_to_your_domain.com/?callback=?&other_data=something,
function(data){
//do something
}
);
Here we pass your normal GET params as well as callback=?. You will return the following from your server:
require('url');
var r = url.parse(req.url,true);
r.query.callback + '(' + some JSON + ')'
3) If you don't care about all browser compatibility you can use CORS:
You can see a much better example than I would be able to write Here
Cross domain ajax requires special support from your server.
Either CORS: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Which not all browsers support yet. It involves special headers in both the request and response that tell the browser that one domain is allowed to communicate with the other, and for what data.
Or JSONP: http://en.wikipedia.org/wiki/JSONP
WHich will work anywhere, but has some implementation limitations. It involves the server wrapping the response in a javascript function callback that will execute and pass in that data you want.
Either way, the server needs to be setup for each of these approaches.
I think your problem is Same Origin Policy. Your browser must get webpage from node.js instance.
Otherwise, you must use something like CORS. There also good question on SO: Ways to circumvent the same-origin policy.

Cross-domain jQuery.getJSON from a Node.JS (using express) server does not work in Internet Explorer

This is an annoying problem, and I don't suppose that it's only IE that has this problem. Basically I have a Node.js server, from which I am making cross-domain calls to get some JSON data for display.
This needs to be a JSONP call and I give a callback in the URL. What I am not sure is, how to do this?
So the website (domainA.com) has an HTML page with a JS script like this (all works fine in Firefox 3):
<script type="text/javascript">
var jsonName = 'ABC'
var url = 'http://domainB.com:8080/stream/aires/' //The JSON data to get
jQuery.getJSON(url+jsonName, function(json){
// parse the JSON data
var data = [], header, comment = /^#/, x;
jQuery.each(json.RESULT.ROWS,function(i,tweet){ ..... }
}
......
</script>
Now my Node.js server is very simple (I'm using express):
var app = require('express').createServer();
var express = require('express');
app.listen(3000);
app.get('/stream/aires/:id', function(req, res){
request('http://'+options.host+':'+options.port+options.path, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // Print the google web page.
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
});
res.end(JSON.stringify(JSON.parse(body)));
}
})
});
How can I change these two so they will work with cross-domain GET in IE? I have been searching the internet and there seem to be a few different things like jQuery.support.cors = true; which does not work. There also seem to be a lot of lengthy workarounds.
There is no real 'ideal' design pattern which I have been able to find for this type of thing.
Seeing as I have control over both the web page and the cross domain web service I'm sending to what is the best change to make to ensure compatability across all IE versions along with FireFox, Opera, Chrome etc?
Cheers!
Say we have two servers, myServer.com and crossDomainServer.com, both of which we control.
Assuming we want a client of myServer.com to pull some data from crossDomainServer.com, first that client needs to make a JSONP request to crossDomainServer.com:
// client-side JS from myServer.com
// script tag gets around cross-domain security issues
var script = document.createElement('script');
script.src = 'http://crossDomainServer.com/getJSONPResponse';
document.body.appendChild(script); // triggers a GET request
On the cross-domain server we need to handle this GET request:
// in the express app for crossDomainServer.com
app.get('/getJSONPResponse', function(req, res) {
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end("__parseJSONPResponse(" + JSON.stringify('some data') + ");");
});
Then in our client-side JS we need a global function to parse the JSONP response:
// gets called when cross-domain server responds
function __parseJSONPResponse(data) {
// now you have access to your data
}
Works well across a wide variety of browsers, IE 6 included.
The following code shows how to handle the GET request (using express) and how to wrap the JSON response using the callback given:
app.get('/foo', function(req, res){
res.header('Content-Type', 'application/json');
res.header('Charset', 'utf-8')
res.send(req.query.callback + '({"something": "rather", "more": "pork", "tua": "tara"});');
});

Categories