Node.js app giving ERR_EMPTY_RESPONSE - javascript

I'm having serious issues with an app I am building with Node.js, Express, MongoDB and Mongoose. Last night everything seemed to work when I used nodemon server.js to `run the server. On the command line everything seems to be working but on the browser (in particular Chrome) I get the following error: No data received ERR_EMPTY_RESPONSE. I've tried other Node projects on my machine and they too are struggling to work. I did a npm update last night in order to update my modules because of another error I was getting from MongoDB/Mongoose { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND'}. I used the solution in this answer to try and fix it and it didn't work and I still get that error. Now I don't get any files at all being served to my browser. My code is below. Please help:
//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create an express app
var app = express();
app.use(express.static('/public/css', {"root": __dirname}));
//create a database
mongoose.connect('mongodb://localhost/__dirname');
//connect to the data store on the set up the database
var db = mongoose.connection;
//Create a model which connects to the schema and entries collection in the __dirname database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//start the server on the port 8080
app.listen(8080);
//The routes
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
//create an express route for the home page at http://localhost:8080/
app.get('/', function(req, res) {
res.send('ok');
res.sendFile('/views/index.html', {"root": __dirname + ''});
});
//Send a message to the console
console.log('The server has started');

//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
These routes don't send anything back to the client via res. The bson error isn't a big deal - it's just telling you it can't use the C++ bson parser and instead is using the native JS one.
A fix could be:
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {
if (err) {
res.status(404).json({"error":"not found","err":err});
return;
}
res.json(data);
});
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
res.status(500).json({ error: "save failed", err: err});
return;
} else {
res.status(201).json(newMonth);
};
});
});

updated june 2020
ERR_EMPTY_RESPONSE express js
package.json
"cors": "^2.8.4",
"csurf": "^1.9.0",
"express": "^4.15.4",
this error show when you try to access with the wrong HTTP request. check first your request was correct
maybe your cors parameter wrong

Related

Getting cannot POST / error in Express

I have a RESTful API that I am using postman to make a call to my route /websites. Whenever I make the call, postman says "Cannot POST /websites". I am trying to implement a job queue and I'm using Express, Kue(Redis) and MongoDB.
Here is my routes file:
'use strict';
module.exports = function(app) {
// Create a new website
const websites = require('./controllers/website.controller.js');
app.post('/websites', function(req, res) {
const content = req.body;
websites.create(content, (err) => {
if (err) {
return res.json({
error: err,
success: false,
message: 'Could not create content',
});
} else {
return res.json({
error: null,
success: true,
message: 'Created a website!', content
});
}
})
});
}
Here is the server file:
const express = require('express');
const bodyParser = require('body-parser');
const kue = require('kue');
const websites = require('./app/routes/website.routes.js')
kue.app.listen(3000);
var app = express();
const redis = require('redis');
const client = redis.createClient();
client.on('connect', () =>{
console.log('Redis connection established');
})
app.use('/websites', websites);
I've never used Express and I have no idea what is going on here. Any amount of help would be great!!
Thank you!
The problem is how you are using the app.use and the app.post. You have.
app.use('/websites', websites);
And inside websites you have:
app.post('/websites', function....
So to reach that code you need to make a post to localhost:3000/websites/websites. What you need to do is simply remove the /websites from your routes.
//to reach here post to localhost:3000/websites
app.post('/' , function(req, res) {
});

Node.js parsing form data using formidable

Hey guys I am new to node, and trying to setup a file/image upload script.
I was able to setup node on my VPS and following this example I also set up the app and it is working great.
https://coligo.io/building-ajax-file-uploader-with-node/
It is using formidable and express
However I'd love to also parse a form where people can add their name and the files get uploaded into a folder containing their names.
I was able to get the folder creation working using mkdirp, however even after many hours of research (formidable api, express api, and more) I can't get the form to parse the name.
I suspect that the upload.js (which sends the data to the node app) does not work.
At the moment a new folder with a random string is created for each upload, but I'd love to be able to parse the entered formname.
Any idea how to get it working? I'd appreciate any help/hints.
app.js
var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var mkdirp = require('mkdirp');
var crypto = require("crypto");
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'views/index.html'));
});
app.post('/upload', function(req, res){
var ordner = crypto.randomBytes(20).toString('hex');
mkdirp('/home/myfolder/fileupload/'+ordner, function (err) {
if (err) console.error(err)
else console.log(ordner)
});
var form = new formidable.IncomingForm();
form.multiples = true;
form.uploadDir = path.join(__dirname, '/'+ ordner);
form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name + Date.now()+'.jpg'));
});
form.on('field', function(field, userName) {
console.log(userName);
});
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
form.on('end', function() {
res.end('success');
});
form.parse(req);
});
var server = app.listen(3000, function(){
console.log('Server listening on port 3000');
});
Thanks
The upload.js is unchanged and I simply added another input to the view.
You can do this by sending the parameters through the POST like so
app.post('/upload/:userName', function(req, res){
var username = req.params.userName
mkdirp('/home/myfolder/fileupload/'+username, function (err) {
if (err) console.error(err)
else console.log(ordner)
});
The rest of your code pretty much stays the same.
EDIT: Your ajax would look something like this
var username = 'GetThisValueFromTheUser'
$.ajax({
url: '/upload'+username,
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful!');
}
});
Note: You can send parameters by using /:parameter in your POST or GET requests, from then on it is easy to use those parameters however you want.

can't delete record from mongodb dbase using backbone.js

Following "Developing Backbone js" http://addyosmani.github.io/backbone-fundamentals/#talking-to-the-server (search "parse function")
on click "Delete": the book is not deleted from the server (dbase) even with this "parse" function operating OK... the DELETE http command is given, with the correct ID for the book... but this doesn't delete it from the dbase...
generated URL command looks like this:
DELETE http://localhost:4711/api/books/5417ff846b205d9c05000001
... this is triggering the following function in server.js
app.delete( '/api/books/:id', function( request, response ) {
console.log( 'Deleting book with id: ' + request.params.id );
...
... but the DELETE command never "returns" (in FF Console you just get the spinner, which doesn't go away)...
In your server.js, setup your server as follows:
// Module dependencies.
var application_root = __dirname,
express = require("express"), // Web framework
path = require("path"), // Utilities for dealing with file paths
mongoose = require('mongoose'); // MongoDB integration
//Create server
var app = express.createServer();
// Configure server
app.configure(function () {
app.use(express.bodyParser()); // parses request body and populates req.body
app.use(express.methodOverride()); // checks req.body for HTTP method overrides
app.use(app.router); // perform route lookup based on url and HTTP method
app.use(express.static(path.join(application_root, "public"))); // Where to serve static content
app.use(express.errorHandler({ dumpExceptions:true, showStack:true })); // Show all errors in development
});
//Start server
app.listen(4711, function () {
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
// Connect to database
mongoose.connect('mongodb://localhost/library_database');
//Schemas
var Book = new mongoose.Schema({
title:String,
author:String,
releaseDate: Date
});
//Models
var BookModel = mongoose.model('Book', Book);
Try creating the delete route as follows:
app.delete('/api/books/:id', function(req, res){
console.log('Deleting book with id: ' + req.params.id);
return BookModel.findById(req.params.id, function(err, book){
return book.remove(function(err){
if(!err){
console.log('Book removed');
return res.send('');
} else {
console.log(err);
}
});
});
});
And test it via AJAX:
$.ajax({
url:'/api/books/5417ff846b205d9c05000001',
type: 'DELETE',
success:function(data, textStatus, jqXHR){
console.log("Post resposne:");
console.dir(data);
console.log(textStatus);
console.dir(jqXHR);
}
});

How do I use node-mongodb-native to connect to Modulus.io?

First question here, so be kind ;)
I am configuring a Node.js server to connect to a MongoDB database in Modulus.io node.js hosting (really good stuff, worth checking it out), but I can't seem to properly stablish connection. Per the getting-started guide I get a connection uri in the format:
mongodb://user:pass#mongo.onmodulus.net:27017/3xam913
But that doesn't seem to work with the structure of the code I was trying to port to the server (had it running locally) because of the Server class argument structure with only host and port to define...
This is the code I am trying to adapt to the connection:
// server setup
var mongo = require('mongodb'),
mdbServer = mongo.Server,
mdbDb = mongo.Db,
mdbObjectID = mongo.ObjectID;
// open a connection to the mongoDB server
var mdbserver = new mdbServer('localhost', 27017, {auto_reconnect: true});
// request or create a database called "spots03"
var db = new mdbDb('spots03', mdbserver, {safe: true});
// global var that will hold the spots collection
var spotsCol = null;
// open the database
db.open(function(err, db) {
if(!err) {
// if all cool
console.log("Database connection successful");
// open (get/create) a collection named spotsCollection, and if 200,
// point it to the global spotsCol
db.createCollection(
'spotsCollection',
{safe: false}, // if col exists, get the existing one
function(err, collection) {spotsCol = collection;}
);
}
});
Any help would be much appreciated, thanks!
Looks like a couple of things:
The connection URL should be mongo.onmodulus.net
var mdbserver = new mdbServer('mongo.onmodulus.net', 27017, {auto_reconnect: true});
rounce is correct, the database name is auto-generated by Modulus.
var db = new mdbDb('3xam913', mdbserver, {safe: true});
Modulus databases will need authentication. Before you call createCollection, you'll have to call auth and pass it the user credentials that are setup on the project dashboard.
I'm a Modulus developer, and I know the DB name thing is not ideal.
Edit: here's full source for a working example. It records every HTTP request and then sends all requests back to the user.
var express = require('express'),
mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db;
var app = express();
var server = new Server('mongo.onmodulus.net', 27017, { auto_reconnect: true });
var client = new Db('piri3niR', server, { w: 0 });
client.open(function(err, result) {
client.authenticate('MyUser', 'MyPass', function(err, result) {
if(!err) {
console.log('Mongo Authenticated. Starting Server on port ' + (process.env.PORT || 8080));
app.listen(process.env.PORT || 8080);
}
else {
console.log(err);
}
});
});
app.get('/*', function(req, res) {
client.collection('hits', function(err, collection) {
collection.save({ hit: req.url });
// Wait a second then print all hits.
setTimeout(function() {
collection.find(function(err, cursor) {
cursor.toArray(function(err, results) {
res.send(results);
});
});
}, 1000)
});
});
Wrong database name perhaps?
From the MongoDB docs on the subject '3xam913' is your database name, not 'spots03'.
var db = new mdbDb('3xam913', mdbserver, {safe: true});

How to push out requested data from mongodb in node.js

I'm working with Node.js, express, mongodb, and got stuck on this data passing between frontend and backend.
Note: code below is middleware code for front- and backend communication
Here I successfully get the input value from the frontend by using req.body.nr
exports.find_user_post = function(req, res) {
member = new memberModel();
member.desc = req.body.nr;
console.log(req.body.nr);
member.save(function (err) {
res.render('user.jade', );
});
};
Here is the problem, I need to use the input value I got to find the correct data from my database(mongodb in the backend) and push out to the frontend.
My data structure {desc : ''}, the desc is correspond to the input value so it should look something like this {desc: req.body.nr} which is probably incorrect code here?
exports.user = function(req, res){
memberModel.find({desc: req.body.nr}, function(err, docs){
res.render('user.jade', { members: docs });
});
};
Would love to have some help.
Thanks, in advance!
Have a look at this great tutorial from howtonode.org.
Because as you can see he uses a prototype and a function callback:
in articleprovider-mongodb.js
ArticleProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, article_collection) {
if( error ) callback(error)
else {
article_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
exports.ArticleProvider = ArticleProvider;
in app.js
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.jade', {
locals: {
title: 'Blog',
articles:docs
}
});
})
});
Also make sure you have some error checking from the user input as well as from the anybody sending data to the node.js server.
PS: note that the node, express and mongo driver used in the tutorial are a bit older.

Categories