As the title says, I have a problem with what node.js command prompt says lies in the requestHandlers.js file. I am following the guide in the Node Beginner Book and until now, there have not been any problems with the book - or rather my code.
I have the following input:
index.js:
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
server.js:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
router.js
function route(handle, pathname) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname]();
} else {
console.log("No request handler found for " + pathname);
}
}
exports.route = route;
requestHandlers.js
function start() {
console.log("Request handler "start" was called.");
}
function upload() {
console.log("Request handler "upload" was called.");
}
exports.start = start;
exports.upload = upload;
And I have this output:
"C:\Program Files (x86)\nodejs\requestHandlers.js:1
console.log("Request handler "start" was
SyntaxError: Unexpected identifier
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:\Program Files (x86)\nodejs\index.js:1:153)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)"
I can't really see where the problem lies. I have followed the guide in the book and I have either copy-pasted the code from the book or written it myself. I have doublechecked the code for errors, but have not found any. I have remembered to use \'function\' for instance, so there would not be any mistakes in the code when entering it in node.js.
So any help would be appreciated!
Thanks.
You're mixing the different string markers in JavaScript.
function start() {
console.log("Request handler "start" was called.");
}
function upload() {
console.log("Request handler "upload" was called.");
}
You can use " for the start and end of a string, but something like "Request handler "start" was called."
Is invalid, because you terminate the string at "start and start a new string at "was called.
If start and upload are variables just concatenate the strings with something like this:
"Request handler " + start + " was called."
or change your string to something like this:
"Request handler 'start' was called."
or remove the " around start and upload.
Related
I am trying to run parse server with nodejs in ibm bluemix but it is throwing an error in parse server PromiseRouter file.
PromiseRouter.js:48
throw _iteratorError;
^
ReferenceError: Symbol is not defined
How can i get this resolved
My App .js
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
var port = process.env.PORT || 1337;
// Specify the connection string for your mongodb database
// and the location to your Parse cloud code
var api = new ParseServer({
databaseURI: 'mongodb://IBM_MONGO_DB',
cloud: './cloud/main.js', // Provide an absolute path
appId: 'MYAPPID',
masterKey: 'MYMASTER_KEY', //Add your master key here. Keep it secret!
serverURL: 'http://localhost:' + port + '/parse' // Don't forget to change to https if needed
});
app.use('/parse', api);
app.get('/', function(req, res) {
res.status(200).send('Express is running here.');
});
app.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
Response :
/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/PromiseRouter.js:48
throw _iteratorError;
^
ReferenceError: Symbol is not defined
at PromiseRouter.merge (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/PromiseRouter.js:33:40)
at new ParseServer (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/index.js:137:10)
at Object.<anonymous> (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/app.js:10:11)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
This is the function in PromiseRouter.js that is throwing an error
PromiseRouter.prototype.merge = function (router) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = router.routes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var route = _step.value;
this.routes.push(route);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
};
This is all i have
The reason why Symbol is not found is because it is an ES6 feature that is not supported in your current Node.js build. Check to make sure your Node.js runtime is at least v4 (see compatibility here).
The easy way to ensure your Node.js build on Bluemix is running at least v4.0 is to define your engine variable in your app's package.json file as such:
{ "engines" : { "node" : ">=4.0" } }
After updating your package.json file, re-push your application to Bluemix and it will build it with your defined version of Node.js
I have set the keys to node.js but still i am unable to get it to working.
Can anybody tell me what should i do to make it work properly.
I need to work with https with node.js.
I get the following error.
`tls.js:1127
throw new Error('Missing PFX or certificate + private key.');
^
Error: Missing PFX or certificate + private key.
at Server (tls.js:1127:11)
at new Server (https.js:35:14)
at Object.exports.createServer (https.js:54:10)
at Object.<anonymous> (/var/www/html/fusionmate/nodejs/server.js:4:36)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)`
Hers my code
var
app = require('https').createServer(handler),
io = require('socket.io')(app),
redis = require('redis'),
fs = require('fs'),
redisClient = redis.createClient();
var options = {
key: fs.readFileSync('/etc/apache2/ssl/apache.key'),
cert: fs.readFileSync('/etc/apache2/ssl/apache.crt')
};
app.createServer(options);
app.listen(3000);
console.log('Realtime Chat Server running at http://127.0.0.1:3000/');
function handler (req, res) {
fs.readFile(__dirname + '/index.html', function(err, data) {
if(err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
There are two issues here:
options needs to be passed to https.createServer() as the first argument (with handler being the optional second argument), but you're just passing in a request handler function. For example:
var fs = require('fs');
var options = {
key: fs.readFileSync('/etc/apache2/ssl/apache.key'),
cert: fs.readFileSync('/etc/apache2/ssl/apache.crt')
};
var app = require('https').createServer(options, handler);
// ...
Further down, you're calling createServer() on an https.Server (app) instance, which isn't correct (you've already created a server instance and instances don't have such a method).
I am learning Node.js. I just found about module.exports. It seems to me that this is a way to help keep code clean and maintainable by separating code.
I tried out a few examples and it works. I got to console.log a few things by calling the method and it ran the function that was on another file.
I also learned some socket.io. I have got it to work as well.
I wanted to separate the code so I put all the socket.io connection information in a separate file and called the method on the main server file.
It doesn't work. The only way everything works if all the code is on the same page.
This is what I have:
app.js
var app = require('express')();
var ioConnect = require('./ioConnect.js')
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
ioConnect.ioConnection();
ioConnect.js
function addScore() {
var io = require('socket.io');
io.on('connection', function(socket) {
socket.on('score', function(data) {
socket.emit('addScore', 15);
});
});
}
module.exports.ioConnection = addScore;
At first I got an error that said: "io is not defined" so I added
var io = require('socket.io)(server); and got server is not defined so I tried
var io = require('socket.io'); and got this error:
/root/game/ioConnect2.js:5
io.on('connection', function(socket) {
^
TypeError: Object function Server(srv, opts){
if (!(this instanceof Server)) return new Server(srv, opts);
if ('object' == typeof srv && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.adapter(opts.adapter || Adapter);
this.origins(opts.origins || '*:*');
this.sockets = this.of('/');
if (srv) this.attach(srv, opts);
} has no method 'on'
at Object.addScore [as ioConnection] (/root/game/ioConnect2.js:5:16)
at Object.<anonymous> (/root/game/app:8:19)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
If I put the code together on one file everything works. Can someone please explain to me exactly whats going on here and what I need to do?
When you require socket.io it returns a function. In app.js you called that require/function with an argument and stored the return value in 'io'. Good so far. In ioConnect.js you are storing the function itself in io. rather than do that, you should pass the io you set in app.js to the function returned by your require of ioConnect.js.
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var ioConnect = require('./ioConnect.js')(io);
server.listen(80);
ioConnect.addScore();
ioConnect.js
function ioConnection(io) {
if (!(this instanceof ioConnection)) {
return new ioConnection(io);
}
this.io = io;
}
ioConnection.prototype.addScore = function() {
this.io.on('connection', function (socket) {
socket.on('score', function (data) {
socket.emit('addScore', 15);
});
});
}
module.exports = ioConnection;
When I try to start following script:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8000);
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log(ip)
I get following Error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
ReferenceError: req is not defined
at Object.<anonymous> (/home/ubuntu/IPDeliverer/server.js:9:10)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:32)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:41)
My first guess was, that there is some module missing, so I installed the following module like this:
npm install req
and then I included following line
var req = require("./node_modules/req/node_modules/request");
but it is still not working. Any suggestions ?
You've named the Request request, not req, also every callback has it's own request, so checking the IP outside the callback like that doesn't make sense. Use request inside the callback instead:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
console.log(ip)
}).listen(8000);
The variable req is not defined there. You have to move it inside of a request handler. Try this:
var http = require("http");
http.createServer(function(request, response) {
var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
console.log(ip)
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8000);
I'm trying this code:
var connect = require("connect");
var io = require("socket.io");
var spawn = require("child_process").spawn;
var server = connect.createServer(
connect.favicon(),
connect.logger(),
connect.staticProvider(__dirname + '/public')
);
server.listen(8000);
var socket = io.listen(server, {flashPolicyServer: false});
var tail = spawn("tail", ["-f", "./nohup.out"]);
tail.stdout.on("data", function(data) {
socket.broadcast(data.toString("utf8"));
});
But when I try to run this I got an error:
Nathan-Camposs-MacBook-Pro:log Nathan$ node app.js
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object function createServer() {
if ('object' == typeof arguments[0]) {
return new HTTPSServer(arguments[0], Array.prototype.slice.call(arguments, 1));
} else {
return new HTTPServer(Array.prototype.slice.call(arguments));
}
} has no method 'staticProvider'
at Object.<anonymous> (/Users/Nathan/Sites/log/app.js:8:10)
at Module._compile (module.js:407:26)
at Object..js (module.js:413:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at Array.<anonymous> (module.js:426:10)
at EventEmitter._tickCallback (node.js:126:26)
Nathan-Camposs-MacBook-Pro:log Nathan$
I don't really know the connect library. But this documentation says, that it's static not staticProvider (in the version 1.0).
So your server creating part should be:
var server = connect.createServer(
connect.favicon(),
connect.logger(),
connect.static(__dirname + '/public')
);