I am working on to do list app using mongoDB and node.js. Basically you type what you want to do then click add. I successfully connected the database but it doesn't show the text that's in the database. It shows only the bullets in the localhost.
Here's the code:
app.get('/', function(req, res) {
db.collection('list').find().toArray(function (err, result) {
console.log(result);
if (err) {return};
console.log(err);
res.render('index.ejs', {list: result})
});
});
app.post('/', function(req, res){
console.log(req.body);
db.collection('list').save(req.body, function(err, result) {
if (err) {return};
console.log(err);
console.log('saved')
res.redirect('/');
})
})
I have validated the code you posted and have revised it slightly with comments.
I hope this helps but it seems that the fault might be in the res.render method that is being used. Please refer to the following code:
// Requires
var express = require('express');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
// Instantiation
var app = express();
var mongopath = "mongodb://localhost:27017/BitX";
// Port number the REST api works on
var portnum = 7500;
// MongoDB object
var db = null;
MongoClient.connect(mongopath, function(err,ldb){
db = ldb;
});
// Implement Body Parser
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
// Start the REST service
var server = app.listen(portnum, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Content Provider Service listening at http://%s:%s", host, port);
});
// Default route
app.get('/', function(req, res) {
// Find all items in orders and send back results to a front end
db.collection('orders').find().toArray(function (err, result) {
res.send(result);
// Consider that the rendering engine may not be functioning correctly
// SEE MORE: https://stackoverflow.com/questions/21843840/what-does-res-render-do-and-what-does-the-html-file-look-like
//res.render('index.ejs', {list: result})
});
});
// Accept a post on the root
app.post('/', function(req, res){
//Save into orders
db.collection('orders').save(req.body, function(err, result) {
res.send(true);
//res.redirect('/');
});
});
For additional information on the res.render method please have a look at:
What does "res.render" do, and what does the html file look like?
- if you have not already.
Hope it helps!
Related
I am trying to perform an INSERT into my SQL Server through my NODE.js server
but it is not working.
I believe it is not a connection problem because (as I will demonstrate at the end of the post) I did a select that worked, so I must be making some mistake in the node.js code.
This is the first javascript system I create.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function (req, res) {
var body = req.body;
var sql = require("mssql");
console.log("C1");
sql.connect('mssql://login:pswd#serv/db', function (err) {
if (err) console.log(err);
// create Request object
console.log("Connected!");
var insert = "INSERT into dbo.WIDS_API_TEST (Programm, ID, Titlw) VALUES ('Teste 1 2 3 ', '39', 'Finance')"
// query to the database and get the records
sql.query(insert, function (err, result) {
if (err) console.log(err)
// send records as a response
console.log("1 record inserted");
});
});
});
//var server = app.listen(5000, function () {
// console.log('Server is running..');
//});
What am I doing wrong? Because the INSERT did not even show my console.logs =/
When I performed a test doing a select it worked, so
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
/* var config = {
user: 'papercut',
password: 'Portage.2018',
server: 'devsqlcl2:1433',
database: 'AgrM6',
port: "1433",
dialect:",ssql",
dialectOptiond:"SQLEXPRESS"
};*/
// connect to your database
sql.connect('mssql://login:pswd#server:1433/database', function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from dbo.balance_papercut', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
This SELECT statement worked.
I'm new in javascript and I want to use webix.
I saw the get started and it's Ok...
So, my problem is that I can't display data from mongodb.
This is my server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
//connect to the mongo
var db = require('mongoskin').db("mongodb://localhost:27017/test", { w: 0});
db.bind('sites');
//create the app instance
var app = express();
//serve static files
app.use(express.static(path.join(__dirname, 'public')));
//parse POST data
app.use(bodyParser.urlencoded({ extended: false }));
// // parse application/json
app.use(bodyParser.json());
function after_update(err, res, record){
if (err){
res.status(500);
res.send({ error:err.toString() });
} else {
res.send(record || {});
}
}
//data loading
app.get('/data', function(req, res){
db.record.find().toArray(function(err, data){
for (var i = 0; i < data.length; i++){
data[i].id = data[i]._id;
delete data[i]._id;
}
res.send(data);
});
});
app.post('/data', function(req, res){
db.record.insert(req.body, function(err, record){
if (err) return res.send({ status:"error" });
res.send({ newid:req.body._id });
});
});
app.put('/data/:id', function(req, res){
db.record.updateById(req.param("id"), req.body, function(err){
if (err) return res.send({ status:"error" });
res.send({});
});
});
app.delete('/data/:id', function(req, res){
db.record.removeById(req.param("id"), req.body, function(err){
if (err) return res.send({ status:"error" });
res.send({});
});
});
app.listen(3000);
and I'm using index.html to display data. Here that it sucks.
my problem is that I can't found the right manner to get the data from my table in mongodb.
I want to display the cars in my DB.
who has an exemple that can help?
Anyone can help please?
Thank you
Try to load the "/data" in the browser. If it shows the valid JSON, check the client-side code of the datatable, it must be something like following
{ view:"datatable", autoConfig:true, url:"/data" }
I see 2 problems in your code (i guess that your collection is "cars" becouse your text):
You are binding a diferent collection than "cars", in the line "db.bind('sites');". You should change for "db.bind('cars');"
You are using the collection "record" to retrieve and write data, in the sentences "db.record.find", "db.record.insert", "db.record.updateById" and "db.record.removeById". You should change for "db.cars.find", "db.cars.insert", "db.cars.updateById" and "db.cars.removeById".
Cheers.
I am pretty new to NodeJS and this is my first time with Express 4, I'm trying to build a simple RESTful front-end around a command-line application. There will ultimately only be one GET and one POST necessary, with the POST handling about 3 or 4 different parameters. The GET should call the command-line application with all default parameters, which is basically just a status check and return the exit status upon completion. The POST will pass along POST parameters on the commandline. I know that this basically calls for an asynchronous call, like child_process.execFile(), but I can't seem to figure out how to actually return the response from within the callback function.
This is the tutorial I used as a starting point, omitting the mongoose dependency, because I have no need for MongoDB, so I basically just followed it up to the point where you start the server. At this point, I'm pretty lost. I always hate writing async code...
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var child_process = require('child_process');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
var router = express.Router(); // get an instance of the express Router
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.get('/myapp/status', function(req, res) {
console.log(req.user);
child_process.execFile(
'casperjs',
['myfile.js', '--cmd="Status"', '--user="myuser"', '--pass="#mypass"'],
null,
function(response) {
// ???
}, res);
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
You can try the following:
router.get('/myapp/status', function(req, res) {
console.log(req.user);
child_process.execFile(
'casperjs', //command
["myfile.js --cmd=Status --user=myuser --pass=#mypass"], // args
function(err, stdout, stderr) { //callback
if (err) {
return res.status(500).send(err);
}
res.send(stdout); // to send response to client
});
});
Following is my server file. I am making 2 calls, one post and one get. It works fine at times. But gives an error of : Can't set headers after they are sent. Does this have anything to do with my client side code?
server.js
var express = require('express')
var mongoose = require('mongoose')
var path = require('path')
var bodyParser = require("body-parser")
var cors = require("cors")
var app = express()
var port = process.env.PORT || 3000
var Url = require("./data/url-schema");
//Express request pipeline
app.use(express.static(path.join(__dirname,"../client")))
app.use(bodyParser.json())
app.use(cors());
/*
Your server must be ready to handle real URLs. When the app first loads at / it will probably work, but as the user navigates around and then hits refresh at /dashboard your web server will get a request to /dashboard. You will need it to handle that URL and include your JavaScript application in the response.
*/
app.get('*', function (request, response, next){
response.sendFile(path.resolve(__dirname, '../client', 'index.html'))
next()
})
app.get('/:code', function(req, res) {
console.log("reg", req.params.code)
Url.findOne({code:req.params.code}, function(err, data){
console.log("data", data)
if(data)
res.redirect(302, data.longUrl)
else
res.end()
})
})
app.post('/addUrl', function (req, res, next) {
console.log("on create");
Url.findOne({longUrl:req.body.longUrl}, function(err, data) {
if (err)
res.send(err);
else if(data) {
console.log("already exists",data)
res.send("http://localhost:3000/"+data.code);
} else {
var url = new Url({
code : Utility.randomString(6,"abcdefghijklm"),
longUrl : req.body.longUrl
});
console.log("in last else data created",url)
url.save(function (err, data) {
console.log(data)
if (err)
res.send(err);
else
res.send("http://localhost:3000/"+data.code);
});
}
});
})
app.listen(port, function () {
console.log('Example app listening on port 3000!')
});
// Connect to our mongo database
mongoose.connect('mongodb://localhost/shortUrl');
I get the Following error
error
_http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/opt/lampp/htdocs/url-shortener/node_modules/express/lib/response.js:718:10)
at ServerResponse.location (/opt/lampp/htdocs/url-shortener/node_modules/express/lib/response.js:835:8)
at ServerResponse.redirect (/opt/lampp/htdocs/url-shortener/node_modules/express/lib/response.js:874:8)
at Query.<anonymous> (/opt/lampp/htdocs/url-shortener/server/server.js:30:8)
at /opt/lampp/htdocs/url-shortener/node_modules/mongoose/node_modules/kareem/index.js:177:19
at /opt/lampp/htdocs/url-shortener/node_modules/mongoose/node_modules/kareem/index.js:109:16
at process._tickCallback (node.js:355:11)
From the execution order, in * route handler, the body is being assigned to the response and then in /:code, the response code 302 is being added, where Location header is also added, hence the error. Any header must be added before the body to the response.
To solve this problem, simply change the order of the two GET statements.
Finally found the solution:
var express = require('express')
var mongoose = require('mongoose')
var path = require('path')
var bodyParser = require("body-parser")
var app = express()
var port = process.env.PORT || 3000
var Url = require("./data/url-schema")
var Utility = require("./utility")
//Express request pipeline
app.use(express.static(path.join(__dirname,"../client")))
app.use(bodyParser.json())
/*
Your server must be ready to handle real URLs. When the app first loads at / it will probably work, but as the user navigates around and then hits refresh at /dashboard your web server will get a request to /dashboard. You will need it to handle that URL and include your JavaScript application in the response.
*/
app.get('/dashboard', function (request, response, next){
response.sendFile(path.resolve(__dirname, '../client', 'index.html'))
next()
})
app.get('/about', function (request, response, next){
response.sendFile(path.resolve(__dirname, '../client', 'index.html'))
next()
})
app.get('/:code', function(req, res) {
Url.findOne({code:req.params.code}, function(err, data){
if(data){
res.redirect(302, data.longUrl)
}
})
})
app.post('/addUrl', function (req, res, next) {
Url.findOne({longUrl:req.body.longUrl}, function(err, data) {
if (err){
res.send(err)
}
else if(data) {
res.send("http://localhost:3000/"+data.code);
} else {
var newCode = getCode()
checkCode(newCode)
.then(function(data){
var url = new Url({
code : data,
longUrl : req.body.longUrl
});
url.save(function (err, data) {
if (err)
res.send(err);
else
res.send("http://localhost:3000/"+data.code);
});
})
}
});
})
app.listen(port, function () {
console.log('Example app listening on port 3000!')
});
// Connect to our mongo database
mongoose.connect('mongodb://localhost/shortUrl');
//Generate a random code
function getCode() {
return Utility.randomString(6,"abcdefghijklmnopqrstuvwxyz")
}
//Check if the code is unique
function checkCode(code) {
return new Promise(function (resolve, reject){
Url.findOne({code:code}, function(err, data) {
if(err === null){
resolve(code)
}else if(data){
saveUrlCode(getCode())
}
})
})
}
My earlier route which was :
app.get('*', function (request, response, next){
response.sendFile(path.resolve(__dirname, '../client', 'index.html'))
next()
})
The get route was getting executed twice on account of the above call and the
app.get(":/code") call.
So I had to handle the routes properly which I have done by handling the dashboard and about routes separately instead of using the "*" route.
I am using NodeJS and ExpressJS to implement a RESTful API server for a simple backend. I am also using BackboneJS to render views in the front. Therefore, right now I have a single index.html file that I want to render when the client sends a /GET to the '/' route. This is what I have so far:
var express = require('express');
var app = express();
app.use(express.bodyParser());
var mongo = require('mongodb');
var mongoose = require('mongoose');
var Server = mongo.Server,
DB = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new DB('mydb', server, {safe: true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'mydb' database");
db.collection('items', {safe:true}, function(err, collection) {
if (err) {
console.log("Creating collection 'items'");
}
});
}
});
var port = process.env.PORT || 3000;
app.engine('.html');
var listItems = function(req, res){
db.collection('items', function(err, collection){
var items = collection.find();
console.log(items);
res.send(items);
});
}
var itemDetails = function(req, res){
}
var deleteItem = function(req, res){
}
var createItem = function(req, res){
}
var updateItem = function(req, res){
}
var routeHome = function(req, res){
// What can I do here to render a plain .html file?
}
app.all('*', function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Content-Type", "application/json");
next();
});
app.get('/', routeHome);
app.get('/items', listItems);
app.get('/items/:id', itemDetails);
app.del('/users/:id', deleteItem);
app.post('/users', createItem);
app.put('/users/:id', updateItem);
app.listen(port);
console.log("Server started up on port " + port);
As you can see I have everything set up except I cannot figure out how to send a regular .html file to the client. I do not need a rendering engine because Backbone is doing all that for me. I just want to get index.html to go to the client.
How about just using the express.static middleware? Since you're using Backbone, you might have the need for sending static JS files as well:
app.use(express.static(__dirname));
Place that somewhere before your other routes. It will try and find files requested in __dirname (the directory where your app.js file resides, but you can of course change the location where the middleware will try and find files), including index.html.
Step One, Remove app.engine(".html"),
Step Two:
var routeHome = function(req, res){
// Do What Ever
res.sendFile("index.html",function(err){ // Transfer The File With COntent Type Text/HTML
if(err){
res.end("Sorry, Error.");
}else{
res.end(); // Send The Response
}
})
}