I'm trying to make a simple form, with user name and last name, and when the user submit information, another page is displayed. I did a form in html, but I'm not sure about what to do next? Does anyone have a small, self-contained example of a form, using node js?
This example does not quite complete your task. But it is a self contained node.js program that displays a form and a different page upon form receipt.
Copy it into a file and then run node filename.js and then go to http://localhost:3000 in a browser.
Take note of the asynchronous code structure. I define a handler function but don't execute it immediately. We instead pass the function to http.createServer and then call .listen(3000). Now when an HTTP request comes in, the http server will pass a req, res pair to the handler function. req is the request object (this will contain the form data; see this question for some hints on how to get that data out. (I suggest that you jump right in and build a small Express app. It's a really nice framework.)
//app.js
// Load the built in 'http' library
var http = require('http');
var util = require('util');
// Create a function to handle every HTTP request
function handler(req, res){
if(req.method == "GET"){
console.log('get');
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end("<html><body><form action='/' method='post'><input type='text' name='hello'><input type='submit'></form></body></html>");
} else if(req.method == 'POST'){
console.log('post');
// Here you could use a library to extract the form content
// The Express.js web framework helpfully does just that
// For simplicity's sake we will always respond with 'hello world' here
// var hello = req.body.hello;
var hello = 'world';
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end("<html><body><h1>Hello "+hello+"!</h1></body></html>");
} else {
res.writeHead(200);
res.end();
};
};
// Create a server that invokes the `handler` function upon receiving a request
// And have that server start listening for HTTP requests
// The callback function is executed at some time in the future, when the server
// is done with its long-running task (setting up the network and port etc)
http.createServer(handler).listen(3000, function(err){
if(err){
console.log('Error starting http server');
} else {
console.log('Server listening on port 3000');
};
});
Related
I'm still new to Node so I'm sure I'm doing something wrong, but some searching isn't helping so here we are.
I'm making a request to an API to get weather data. I can get the data and log it to the console no problem, but I'm having trouble getting the body of the request to end up in the response to the original POST.
var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// make the web server use body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
console.log("server starting on " + appEnv.url);
});
// Send information from the weather API to the console
app.post('/processWeather', function (req, res) {
requestString = 'http://api.openweathermap.org/data/2.5/weather?id=7839805&appid=xxxxxxxx';
request(requestString, function(err, res, body){
if (!err && res.statusCode == 200) {
console.log(body);
}
});
//redirect back to homepage after getting the weather
res.redirect("/");
});
So the problem with this is that I can't simply use the body variable in the app.post callback. I'm suspicious this is to do asynchronous logic but I'm as I'm new I can't wrap my head around the best way to do this without using a global variable to temporarily store the body variable. How can I get the contents of the body variable sent back to the browser? Any help greatly appreciated. Cheers.
Don't use global variables unless it's absolutely necessary!
You can use session.
req.session['weather'] = weatherData; // Weather data
res.redirect("/");
You can use a lot of other ways also. But this is what I'd prefer.
I figured out what I needed. All I had to do was place the request in the res.send
res.send(request(requestString));
I am unable to send the res (request object) between functions. The following code is executed by my app.js (main express middleware):
//app.js calls File.js
//File1.js
var file2 = require('./File2.js);
export.modules = function (req,res,next) {
file2(data) {
res.send(data); //<-- this is not working
}
}
//File2.js
export.modules = function(data){
data = 'test';
}
Also I do not understand when to use next() or when to use res.end().
Its really hard to understand from you code snippets, so i will address your second question regarding next vs send
You use next inside your middlewares, which means you dont want yet to respond to your client with data, but you want to proccess the data from another middleware down the line, when you reach your final middleware you need to use res.send();
note that you cannot use res.send multiple times, so you must call it when you finished your processing and want to respond the data to the user.
you must use middleware with express as following:
var app = express();
app.use(function(req,res, next){
// some proccessing
req.proccessData = "12312312";
next();
})
app.use(function(req,res, next){
// here you respond the data to the client
res.send(req.proccessData);
})
You can also use this with routes(get, post and etc...) Just add next as third param to the route when you want to send data to next stage
I'm using MEAN stack with MeanJs. The thing is, I have a task that requires calling a GET request from the server side (Expressjs) to another server (with a different domain name).
The code in the client side (AngularJs) calls:
$scope.getWorkflow = function() {
$http.get('/ezee', $scope.credentials).success(function(response) {
console.log(response.message);
}).error(function(response) {
console.log('error');
});
};
And the corresponding server controller function is:
exports.list = function(req, res) {
req.get('http://ezslave.io', function(q, r){
res.json({message: r.message}); // just to test
});
};
Obviously, the code below doesn't work. I'm unsure about how to make a GET request from that list function. Am I supposed to use ExpressJs or pure NodeJs for this? And how to get the correct library loaded?
Use the request module of nodejs : https://github.com/mikeal/request
for sending the http request.
var request = require("request");
exports.list = function(req, res) {
request("http://ezslave.io",function(err,response,body){
res.send(response);
});
};
Hope this helps you
From one of the machines in my network (client), I am making $.ajax() request to my Nodejs server like,
//Client : index.html
$.ajax({
type:"post",
url:'http://192.168.2.6:8080',
data:JSON.stringify({"loginData":{"uanme":"maverick","upass":"asd"}}),
success:function(data){console.log(data);alert(data);},
error:function(){alert('Error aala');}
});
AND my Nodejs server is
//listener.js
var server = require('http').createServer(function (request, response) {
var body='';
if(request.method=='POST'){
request.on('data',function(data){
body+=data;
});
request.on('end',function(){
console.log(body);
});
}
}).listen(8080);
These console.log()s are working absolutely fine. I get the exact same data I am sending on the node side,
Now my question is, in php when we make an $.ajax() request, we use echo in our php file to send the data back to the client,
What should I have to do on server side in Nodejs (listener.js file) if I want to send the data back to the client?
var server = require('http').createServer(function (request, response) {
var body='';
if(request.method=='POST'){
request.on('data',function(data){
body+=data;
});
request.on('end',function(){
console.log(body);
//response.setHeader("Content-Type", ""); set the header to your content type
response.write('foo'); // <-----
response.end('Dear client, I have cake for you'); // <-----
});
}
}).listen(8080);
Further reading Node.js Documentation
Solved this problem myself.
The problem was with cross domain ajax requests.
I don't know why this was happening, even though I had specified url:localhost:8080 in my $.ajax call...
Solved the problem my adding
response.setHeader("Access-Control-Allow-Origin", "*");
in my response headers.
PEACE
Node.js server
var http = require("http");
http.createServer(function(request,response){
console.log("client connected");
response.writeHeader(200,{"Content-type": "text/html"});
response.write("Hello ;-)");
response.end();
}).listen(9090);
I try to load the server output into a div with the ID "myDisplayField":
$("#myDisplayField").load("http://localhost:9090");
(The HTML-File lies on my local httpd)
The issu I'm having with that is that the node server may show that he got a request from ajax ("client connected"), but "Hello ;-)"/the site content doesn't get loaded into #myDisplayField as expteced.
If I set up a webserver like Apache and put a index.html with "Hello ;-)" in htdocs, the whole thing works just fine.
What am I doing wrong?
I just tried your code, and navigating to localhost:9090 displays the 'hello' body as expected.
It may be that jquery's load() method looks for other data - for example, content-type in the header - that your very simple response doesn't provide. Instead of building every http response individually, you should use a higher-level server like express:
var express = require('express');
var app = express();
app.use(function(req, res, next) {
res.send('Hello');
});
app.listen(9090);