I am reading Professional Node.js and i'm trying to understand connect HTTP middleware framework. I created a simple middleware that returns a function that replies with a custom test string:
function replyText(text) {
return function(req, res) {
res.end(text);
};
}
module.exports = replyText;
But when i try to use this middleware in a connect server. Node gives me an error:
/Users/socomo22/work/hello_world_app_v2.js:8
var app = connect.createServer(replyText('Hello World!'));
^
TypeError: undefined is not a function
But when i simply use:
var app = connect();
app.listen(8080)
It runs without giving any error. I don't understand whether i'm doing any syntatical mistake. How would i use this simple middleware? This is my connect server file:
var connect = require('connect');
// middlewares
var replyText = require('./reply_text');
var app = connect();
var app = connect.createServer(replyText('Hello World!'));
app.listen(8080, function() {
console.log('listening on 8080 port')
});
As pointed by documentation use use API to mount a middleware and a http module to create an instance of server although you can create an instance just with connect as pointed here.
As pointed by #FranciscoPresencia adding .js extension while you require a your local module is optional.
var replyText = require('./reply_text.js');
So your code should look like this and i tested it. Working as intended
var connect = require('connect')
var http = require('http')
var app = connect();
// middlewares
var replyText = require('./reply_text.js');
app.use(replyText('Hello World!'));
http.createServer(app).listen(8080, function() {
console.log('listening on 8080 port')
});
Note: Try to avoid ports like 8080, 80 etc as its a reserved ports that might be used by other apps. This sometimes may cause node to fail.
Adding the output screenshot for your reference
Here You can start server in this way...
var connect = require('connect');
var http = require('http');
var app = connect();
var replyIN = require('./connetFile.js')
app.use(replyIN('Hello there m back again'));
http.createServer(app).listen(8888,function(){console.log('Server has started');});
And this is your connectFile.js
function replyIN(text){
return function (req, res) {
res.end(text);
};
};
module.exports = replyIN;
Related
So I am fairly new to the backend. Anyway, I want to create an API that I can use in the front-end, the error I am facing when I try to send a request to the localhost:5000/elements Postman is giving me Error: connect ECONNREFUSED 127.0.0.1:5000 if someone could help me it would be awesome. Thanks
var fs=require('fs');
var data=fs.readFileSync('books.json');
var elements=JSON.parse(data);
const express = require("express");
const app = express();
const cors=require('cors');
const Port = 5000
app.listen(process.env.Port, () => console.log("Server Start at " + Port));
app.use(express.static('public'));
app.use(cors());
app.get('/elements',alldata);
function alldata(request,response)
{
response.send(elements);
}
app.get('/elements/:element/',searchElement);
function searchElement(request,response)
{
var word=request.params.element;
word=word.charAt(0).toUpperCase()+word.slice(1).toLowerCase();
console.log(word);
console.log(elements[word]);
if(elements[word])
{
var reply=elements[word];
}
else
{
var reply={
status:"Not Found"
}
}
console.log(reply.boil);
response.send(reply);
}
This problem usually happens if you forget to run npm start.
Either way, I recommend moving the app.listen to the bottom of the code. It helps with readability, and it will mount all of code before running the Express server.
Your process.env.Port is also undefined. Change it to const port = process.env.Port || 5000 so you can get a fallback value. Change it also in the app.listen.
Then, define allData and searchElement so they are located before the app.get('/elements'). Finally, after you have done all of this, make sure that the request type in Postman is GET.
process.env.Port is unrelated to Port.
It's
app.listen(Port, () => console.log("Server Start at " + Port));
I have a few questions about configuring socket.io for my node.js application.
When requiring var socket = require('socket.io')( /* HERE */ ), do I need to input the port my server listens where the /* HERE */ is at?
Right below the above line, I have another require function, for a .js file that contains a few constants and a function (see below). When I try to refer to 'socket' in that file it says it's undefined. But since this line is below the require line for the socket.io middleware seen above, why does it say 'undefined'?
const numbers = '1234'
function asd(req,res,next) {
socket.emit('a')
}
module.exports = {
asd
}
For configuring client-side socket.io, I added this line:
var socket = io.connect('https://mydomain')
Do I need to say 'mydomain:port' or is 'mydomain' enough?
This is how you use socket.io
var http = require('http');
var express = require('express');
var path = require('path');
var app = http.createServer();
var io = require('socket.io')(app);
var port = 8081;
io.on('connection', function(socket){
socket.on('event1', function (data) {
console.log(data);
socket.emit('event2', { msg: 'delivered' });
});
});
app.listen(port);
Answer to your second question
Yes, you will need to specify the port you are using
<script src="socket.io.js"></script>
<script>
var socket = new io.Socket();
socket.connect('https://mydomain:8081')
socket.on('your_event',function() {
console.log('your_event receivid from the server');
});
</script>
Here socket will connect to port 8081
This is a simple server side code
var http = require('http');
var io = require('socket.io');
var port = 8081;
// Start the server at port 8081
var server = http.createServer();
server.listen(port);
var socket = io.listen(server);
// example listener
socket.on('event_2', function(client){
console.log('event_2 received');
});
// example emitter
socket.emit('event_1', { hello: 'world' });
I am currently using crypto.js module to hash things. It was working for a while then I started getting this error:
Here is the foundation of my server:
process.stdout.write('\033c'); // Clear the console on startup
var
express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http),
path = require("path"),
colorworks = require("colorworks").create(),
fs = require("fs"),
crypto = require("crypto");
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
http.listen(443, function(){
// Create the http server so it can be accessed via 127.0.0.1:443 in a web browser.
console.log("NJ project webserver is running on port 443.");
// Notify the console that the server is up and running
});
app.use(express.static(__dirname + "/public"));
app.get("/", function(request, response){
response.sendFile(__dirname + "/public/index.html");
});
I am aware that these functions are creating the problem:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
The problem being, if these functions don't work (which they don't anymore), roughly 200 lines of code will go to waste.
This error is triggered by attempting to hash a variable that does not exist:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
md5(non_existent); // This variable does not exist.
What kind of data are you trying to hash ? Where does it come from ?
I would check the value of msg first then I would try :
crypto.createHash('md5').update(msg.toString()).digest('hex');
You could also use these packages instead:
https://www.npmjs.com/package/md5
https://www.npmjs.com/package/js-sha256
i have a main file -- index.js:
var express = require('express');
var app = express();
var request = require('request');
var demo = require('demo');
// This app will only respond requests to the '/scrape' URL at port 3000.
app.get('/scrape', function (req, res) {
var url = "http://www.l.com";
request(url, function (error, response, html) { // two parameters: an URL and a callback
if (!error) {
demo(html);
}
});
});
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);
});
and my module is demo.js:
module.exports = function (html) {
....
return JSON.stringify(json);
}
The error is :
TypeError: demo is not a function
I am new to node.js, i would like to know why this didn't work. Maybe i dont understand the real principle of module?
Thank you for answer me first.
You're not exporting your module properly. It should be:
exports.demo = function ....
Try to include your demo module in index.js:
var demo = require('./demo.js');
For the other freshers who use module in node.js for the first time.
first, made a new module called the name of your module.js
Second, it is not necessary to do "
npm install demo --save", if you want, it is also okay.
Third, in the main js which u want to call this module, focus on the name and the path of the module, you should write var anyName = require('the name of your module');, if they are in the same directory, you should write like this: var anyName = require('./the name of your module');
Bases
I'm trying to use sockets on my node project. This is the how it basically works :
/
|-> controllers/
| |-> home.js
|-> app.js
|-> sockets.js
/app.js
On app, I call sockets.js to start the socket server :
var express = require('express');
var sockets = require('./sockets');
var app = module.exports = express();
var server = app.listen(config.PORT);
var io = sockets(server);
/sockets.js
On this file I start the socket server, and return io.
var socket = require('socket.io');
module.exports = function(server) {
var io = socket.listen(server);
io.sockets.on('connection', function(socket) {
// Here I can call every socket I want (if I have the socket_id) with this code :
var socket = io.to(socket_id);
socket.emit('message', {});
});
return io;
};
Question
But now, I want to retrieve my io server on my home controller and call a specific socket. I've tried to do this :
/controller/home.js
var io = require('../sockets.js');
module.exports = {
home: function(req, res, next) {
var socket = io.to(socket_id);
socket.emit('message', {});
}
};
But I have this error, cause I don't execute the function (but I don't want create a new socket server here) :
TypeError: Object function (server) {
var io = socket.listen(server);
/*.....*/
return io;
} has no method 'to'
I want to get an access to the io variable returned by this function called on app.js. How Can i get it ?
You could convert sockets.js into an object that exposes your io property. You would also add a function listen that app.js calls during initialization.
// sockets.js
module.exports = {
listen: function(server) {
this.io = socket.listen(server);
//...
return this.io;
}
}
Your controller can then access require('../sockets.js').io, You just need to make sure io is defined at the time you use it, or otherwise make sure app.js calls listen before your controller gets invoked.
You must be convert sockets.js into an object that exposes your io property.
You would also add a function listen that app.js calls during initialization.
Your controller can then access require('../sockets.js').io.