i try to create simple express apllication serv.js:
var express = require('express'),
app = express();
app.listen(3000, function() {
console.log('Server is running');
});
and when i run it node serv.js, i've got error:
/home/leonid/proj/first/node_modules/express/lib/application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot call method 'handle' of undefined
at Function.app.handle (/home/leonid/proj/first/node_modules/express/lib/application.js:119:16)
at Server.app (/home/leonid/proj/first/node_modules/express/lib/express.js:28:9)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at Socket.socket.ondata (http.js:1966:22)
at TCP.onread (net.js:527:27)
How can it resolve?
You have to define a route for the server to respond to requests.
var express = require('express'),
app = express();
app.get('/hello.txt', function(req, res){
res.send('Hello World');
});
app.listen(3000, function() {
console.log('Server is running');
});
Related
I am getting an error when calling my router from my routes directory.I have made some changes in my code around some of the other posts on this issue but I can't get anything to solve.However i am not sure what exactly is wrong with my code below.
This is my error
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\app.js:42:5)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:279:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:752:3)
[nodemon] app crashed - waiting for file changes before starting...
I have this code in my app.js
//importing modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//conect to the mongodb
mongoose.connect('mongodb://localhost:27017/shoppinglist');
//on connection
mongoose.connection.on('connected',()=>{
console.log('Connected to database mongodb # 27017');
});
//error
mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('Error in database connection:'+ err);
}
});
//port no
const port = 3000;
//adding middleware - cors
app.use(cors());
//body - parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname, 'public')));
//routes
app.use('/api', route);
//testing server
app.get('/',(req, res)=>{
res.send('foobar');
});
app.listen(port,()=>{
console.log('Server started at port:' + port);
});
I have this code in my route.js
const express = require('express');
const router = express.Router();
const Item = require('../model/shoppingItem');
//retriving data from db
router.get('/items', (req, res, next)=>{
Item.find(function(err, items){
if(err){
res.json(err);
}
else{
res.json(items);
}
});
});
//insert data
router.post('item', (req, res, next)=>{
let newShoppingItem = new Item({
itemName: req.body.itemName,
itemQuantity: req.body.itemQuantity,
itemBought: req.body.itemBought
});
newShoppingItem.save((err, item)=>{
if(err){
res.json(err);
}
else{
res.json({msg: 'Item has been added successfully'});
}
});
});
You are using a module that you never exported.
app.use('/api', route);
but route was never exported - that's your main issue.
in your route module you can wrap everything in export default - alternatively you can use module.exports = router
This is an open source project I was working on try following the structure, if you still have issues let me know.
https://github.com/Muhand/nodejs-server
I'm trying the following code but it's giving me an error, "res.send is not a function". Please help me.
Here's the code:
var http = require('http');
var fs = require('fs');
var connect = require('connect');
var express = require('express');
var app = express();
app.get('/', function(res, req ) {
res.send('Hello World');
});
var server = app.listen(8888, function(){
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
The server is running fine and is connecting. The complete error that is being displayed is something like this:
TypeError: res.send is not a function
at c:\wamp\www\node\server.js:8:13
at Layer.handle [as handle_request] (c:\wamp\www\node\node_modules\express\lib\router\layer.js:95:5)
at next (c:\wamp\www\node\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (c:\wamp\www\node\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\wamp\www\node\node_modules\express\lib\router\layer.js:95:5)
at c:\wamp\www\node\node_modules\express\lib\router\index.js:281:22
at Function.process_params (c:\wamp\www\node\node_modules\express\lib\router\index.js:335:12)
at next (c:\wamp\www\node\node_modules\express\lib\router\index.js:275:10)
at expressInit (c:\wamp\www\node\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (c:\wamp\www\node\node_modules\express\lib\router\layer.js:95:5)
According to the API reference, the first param always contain request req, then response res.
So change first param res to req:
app.get('/', function(req, res) {
res.send("Rendering file")
}
It should fix it.
You've got the res and req parameters the wrong way around.
app.get('/', function(res, req)
should be
app.get('/', function(req, res)
Source: API docs.
Swap req & res : function(req, res)
Everything fine. Good Work. Just make a little change in parameters e.g (req, res) instead of (res, req). Its a Rule.
you should use req argument first and res as the second argument this will work without any issue
app.get('/', function(req, res) {
res.send("Rendering file")
}
You can change your mind in some cases and could be write like this.
note: by default, when you run node server on your local machine. Your host will always be localhost:"your desire port"
Thank you!
const express = require("express")
const app = express();
const port = 8888;
// for redering hello you don't need to require fs
const fs = require("fs")
app.get ('/', (req, res) => {
res.send("hello world")
})
app.listen(port, () => console.log(`Listening on ${port}`))
The middleware function you are writing is a callback function and should follow the order of declaring params function(req, res, next) req for request res for response and next for further operation. You can refer to API reference.
So the proper code would be:
var express = require('express');
var http = require('http');
var fs = require('fs');
var connect = require('connect');
var app = express();
app.get('/', function(req, res) {
res.send('Hello World');
});
var server = app.listen(8888, function(){
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
I have a Problem with my Node.js Server. I want to host a html Document but there is one Problem with a TypeError. I cann't find the mistake. Can you help me?
var express = require("express");
var mysql = require('mysql');
var app = express();
var fs = require("fs");
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
user : 'root',
password : '',
database : 'test',
debug : false
});
app.get('/', function(req, res) {
fs.readFile('index.html', 'utf-8',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
});
app.listen(3000);
console.log("SERVER IS NOW RUNNING AT PORT 3000........");
Here now the log:
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.2\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" Server.js
SERVER IS NOW RUNNING AT PORT 3000........
_http_outgoing.js:430
throw new TypeError('first argument must be a string or Buffer');
^
TypeError: first argument must be a string or Buffer
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:430:11)
at ReadFileContext.callback (c:\........\Server.js:21:13)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:303:13)
Later I want to make a MySQL Connection with Pooling.
You can also use createReadStream and .pipe to res but as #robertklep mentioned, you should check if (err) inside the readFile callback.
Here is the example
var fs = require('fs');
var http = require('http');
var file = fs.createReadStream('/path/to/file');
var server = http.createServer(function (req, res) {
// res.writeHead(200, {
// 'content-type': 'text/plain'
// });
file.pipe(res);
});
server.listen('3000');
UPDATE
So to match your code using express, you don't have to do much:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(3000, function () {
console.log('SERVER IS NOW RUNNING AT PORT 3000........');
});
Just put all your assets in the public folder and you should be good to go. To find more info about Express you can go to http://expressjs.com/en/4x/api.html
I recently implemented socket.io and running into some strange errors.
The error messages I am getting aren't incredibly helpful and trying to figure out what is causing this.
Here are the contents of my app.js -
app.js
// Express Requirements
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
// Formidable Requirements
var formidable = require('formidable');
var util = require('util');
var routes = require('./routes/index');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8888);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// Non Default Code
// Socket.io Code
io.on('connection', function (client) {
console.log("Client connected!");
client.emit('newcommer',{status: true, newuser: 'paul'});
});
// End Socket.io Code
// End Non Default Code
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Error Message
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Object.<anonymous> (/Users/blah/blah/app.js:20:8)
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 Module.require (module.js:364:17)
28 Nov 19:10:39 - [nodemon] app crashed - waiting for file changes before starting...
Does anyone see anything that is off that could be causing this error?
Edits For Culprits:
Once these lines are removed then the code does not produce any errors:
var server = require('http').Server(app);
var io = require('socket.io')(server);
// Socket.io Code
io.on('connection', function (client) {
console.log("Client connected!");
client.emit('newcommer',{status: true, newuser: 'paul'});
});
// End Socket.io Code
Are you sure, you are getting this error ???
I think you have another server running on the same port server.listen(8888);
Either close that running server or changer the port as server.listen(8000);
I've got a simple app which uses socket.io module for node.js.
When i run my server with node express_server.js command it works ok, but when i want to open my http://localhost:8080 page in browser, node throws an error:
/home/tomek/dev/node/node_modules/express/lib/application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot read property 'handle' of undefined
at Function.app.handle (/home/tomek/dev/node/node_modules/express/lib/application.js:119:15)
at Server.app (/home/tomek/dev/node/node_modules/express/lib/express.js:28:9)
at Manager.handleRequest (/home/tomek/dev/node/node_modules/socket.io/lib/manager.js:565:28)
at Server.<anonymous> (/home/tomek/dev/node/node_modules/socket.io/lib/manager.js:119:10)
at Server.EventEmitter.emit (events.js:110:17)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:504:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at Socket.socketOnData (_http_server.js:357:22)
at Socket.EventEmitter.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:156:16)
My express_server.js file looks like:
var express = require('express'),
socket = require('socket.io'),
http = require ('http');
var app = express();
server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);
io.sockets.on('connection', function (client) {
console.log('-- Client connected --');
});
and index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chat application</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var server = io.connect('http://localhost:8080');
</script>
</body>
</html>
There is no router defined. Try add this after creating the app (var app = express()):
app.get('/', function(req, res) {
// res.send('hello world');
res.sendfile('index.html');
});
Express is a framework that amongst other stuff replaces the 'http' module. You appear to be trying to use both together. Try this:
var express = require('express'),
var app = express();
app.get('/', function(req, res) {
res.sendfile('index.html');
});
var port = Number(process.env.PORT || 8080);
app.listen(port, function() {
console.log("Listening on " + port);
});
Credit to Ben for the nudge on the get method.