Node.js server with http get json - node.js

I want to create a simple Node.js server to do the following :
With my application I just do the command http.get(Node.Js_Server_address/json) to get the json file data stored on my server.
Could please help me with a tutorial? Any help would be appreciated!

This is very simple example of node.js server:
var app = require('./app');
var http = require('http');
var server = http.createServer(app);
server.listen(8080, function() {
console.log("listening to: http://127.0.0.1:8080");
});
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
there is a nice tutorial here and here ...
you can use npm to install node.js and all the packages that you need for it.
hope it helps.

There are lots of examples on this topic, i think you should make some googling before next time.
You can create a REST server via express module of nodeJs. In your server folder use npm install express to download express module. You can get more information about express from here. After that create a server.js file in your server folder.In server.js
var express = require('express');
var app = express();
var PORT = 8080;
/* req stands for request, res stands for response */
app.get('/json',function(req,res){
res.json(yourData);
})
app.listen(PORT,function(){
console.log('Express is listening port:' + PORT + '!');
})
So this should do the work. Let me know if this helps you.

Related

express and http server usage togather

Gone through code as below couldnt understand the working of code 1...what is the difference between the two codes below
**
What is the point of using http and express togather in code 1?
Code1
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res)
{
res.sendFile(__dirname+'/index.html');
});
http.listen(3000, function()
{
console.log('listening on *:3000');
});
The same thing can be done as
Code2
var express=require('express');
var app=express();
var socket=require('socket.io');
app.get('/',function(req,res){
res.sendFile(__dirname+'/index.html');
}).listen(8080);
console.log("Listening to port 8080");
You're asking about the difference of expressjs own server and http server. They are different in many ways.
Solved here
The app object conventionally denotes the Express application which is created by top level express() function exported by the Express module.
http.listen(): Starts the HTTP server listening for connection
In the second case it works app.listen() which binds and listens for connection on the specified port and it identical to http.listen()

Why do I need to add "require("http")" when I already have express?

I am trying to follow this tutorial on creating a simple chat application using socket.io. I am at the part of the tutorial where I have to insert all of the code below into a js file and initiate it. I just don't understand why the 2nd of code exist, I heard that express can do a lot more than http. Instead of using the "http.listen" code, can't "app.listen" be used and "app" passed to "io" instead?
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Why do I need to add “require(”http“)” when I already have express?
You don't have to manually load the http module yourself. You use express to create an http server for you (it will load the http module for you) and integrate it with socket.io without manually loading the htttp module like this:
const app = require('express')();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
const server = app.listen(3000, function(){
console.log('listening on *:3000');
});
const io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
});
Internally, app.listen() loads the http module for you, creates a server and then starts it, returning the server object which you can then use with socket.io.
Inside of express, this is the code for app.listen():
const http = require('http');
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, somebody had to load the http module. If you use app.listen(), the express will do it for you.
You are right. Express is a framework that sits on top of the nodejs application and provides a much easier,provided more middleware to handle routes, session and cookies and more efficient way to create server as such
var express = require('express');
var app = express();
app.listen(3000);
In this example, for the purpose of creating a socket between different channels, you have to use HTTP to indicate that the socket is used to handle HTTP requests/responses. You simply can't pass an entire express application to io.

Creating web server with express (node.js)

js and am trying to create a web server and server side code for my web application.
I understand express is used to get access to all static files.
I am trying to start a simple server using express as follows:
var express = require("express");
var url = require("url");
var http = require("http");
var port = 3000;
var app = express();
app.use(express.static(__dirname + "/Client"));
http.createServer(app).listen(port, function(req,res){
console.log("Server running at: " + "http://" + port);
res.writeHead(200,{
"Content-Type":"text/plain"
});
});
I cant seem to do anything with my res variable in my callback, which I am trying to use as a response object. Allowing me to do things like:
res.end(¨hello world¨);
Is this callback even allowed, or how can I start sending responses etc. I am on virtual box (linux) machine, and using res always gives error (undefined methods etc.). Thanks in advance,
http.createServer(app).listen(port, [hostname], [backlog], [callback])
There are no parameters given to the callback function. This is why req and res are undefined.
So you may change your code to:
app.listen(port, function(){
console.log("Server running at: " + "http://localhost:" + port);
});
app.get('/', function(req,res) {
res.status(200).send('Hello World!')
})
So take a look at the documentation of app.listen() and app.get()

Express won't send headers

I've done this from scratch and it still gives me an error...
I've run
express test
then
cd test && npm install
I've edited the app.js adding a route such this:
app.get('/test',function(req,res) {
res.writeHead(200, {"Content-Type": "application/json"});
return res.send('{"a":3}');
});
Then I've run node
node app.js
And when I try to access http://server/test I get
Error: Can't set headers after they are sent.
I'm using
Node v4.2.1, Express 2.5.8, npm 3.4.0.
This just happens with Express, if I create a simple server on Node I can use writeHead.
When res.writeHead(200, {"Content-Type": "application/json"});,you send all the response headers to the client,so you can not send header again.
Because res.send is the function of express's response object,I look the source code of this send function:
chunk is what you send here : String('{"a":3}')
this.set('Content-Type', setCharset(type, 'utf-8')) here express helps us concat our content-type with utf-8 so server needs to send header again
That is why you get the error.
Ps.
Sorry for my bad english and I hope you understand what I try to explain.
What about using res.setHeader
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.setHeader("Content-Type","application/json");
res.send('{}');
});
var server = app.listen(3000, function () {
var host = "localhost";
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

Express.js showing ERR_CONNECTION_REFUSED

I have installed node(v4.1.2) and express(4.13.3)
Node Server code:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
After running the node file and upon calling http://localhost:3000/ gives me ERR_CONNECTION_REFUSED.
Have you run in powershell at server directory?
node app.js
You are listening on port 3000.
So Try http://localhost:3000
At first install Node.js body parsing middleware.
Installation: npm install body-parser
Then add the following lines:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
I think your problem will be solved. For more details, visit -
http://expressjs.com/en/resources/middleware/body-parser.html

Resources