I need to get data from Redis in node server and send it to a Wordpress layout. I tried the following, but data doesn't seem to get sent.
var express = require('express');
var app = express();
var redis = require('redis');
var client = redis.createClient(); //creates a new client
client.on('connect', function () {
console.log('connected');
});
data = [];
client.set(['first', 'Oleh']);
client.set(['second', 'Ivan']);
client.set(['thirt', 'Andriy']);
client.set(['fourth', 'Olena']);
client.set(['fifth', 'Kristy']);
client.set(['sixth', 'Irina']);
client.get('first', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('second', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('thirt', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('fourth', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('fifth', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('sixth', function (err, reply) {
console.log(reply);
data.push(reply)
});
app.get('http://localhost/wordpress/', function (req, res) {
res.type('application/json'); // set content-type
res.send(this.data); // send text response
console.log(this.data);
});
app.listen(process.env.PORT || 4730);
It seems you have the scope incorrect. this.data refers to the function (req, res) {} and not your global scope.
Try doing res.json(data) and remove the res.type(), as res.json already takes care of that for you.
Related
I am fetching data from a MongoDB database then putting it in a cursor to send that as a Node.js response.
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost/EmployeeDB';
/* GET users listing. */
router.get('/', function(req, res, next) {
//res.send('respond with a resource');
MongoClient.connect(url, function(err, db) {
var cursor = db.collection('Employee').find();
cursor.each(function(err, doc) {
console.log(doc);
arrayres = doc ;
res.send(doc);
});
db.close();
});
});
module.exports = router;
It sends only the first record then I get this error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client
at ServerResponse.removeHeader (_http_outgoing.js:528:11)
at ServerResponse.send
Notice: I get this error only when there are multiple records to send as response.
You are sending the response twice. Which is impossible ( look at Why can't we do multiple response.send in Express.js? )
res.send('respond with a resource');
Here and
res.send(arrayres);
Here.
Here is a working example based on jeremy's answer :
router.get('/', function (req, res, next) {
MongoClient.connect(url, function (err, db) {
var cursor = db.collection('Employee').find();
let employees = []
const pushData = async () => {
cursor.forEeach( function (doc) {
employees.push(doc);
});
}
const sendResponse = async () => {
await pushData();
res.json(employees);
}
});
});
You can only send back one response to the browser (be it res.send(), res.end(), res.sendFile(), res.json() or any other). So, you can't have that inside a .forEach().
First, build an array, then send your data back once.
router.get('/', function (req, res, next) {
MongoClient.connect(url, function (err, db) {
var cursor = db.collection('Employee').find();
let employees = []
cursor.forEeach( function (doc) {
employees.push(doc);
});
res.json(employees);
});
});
Or with Mongoose :
Employee.find().lean().exec( (err,docs) => res.json(docs))
I wanna take the whole list of notifies from mongo db but it returns empty([]) array also I know that i need callback or shorter way of it . Do you have any idea for collecting any data from mongodb by node.js? If I call this /Notifies method (http://127.0.0.1:5000/Notifies)
var MongoClient = require('mongodb').MongoClient;
var express = require("express");
var app = express();
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
});
return res.json(arr);
});
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function () {
console.log("Listening on " + port);
})
Don't use for docs.each instead of this use .toArray so it will return directly a array and then use Json.stringify to convert it into json string array
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
coll.find({}).toArray(function (err, result) {
if (err) {
res.send(err);
} else {
res.send(JSON.stringify(result));
}
})
});
The problem is you are returning the empty array from within the function, before the actual DB operation occurs. You need to move the line return res.json(arr);
into the find function:
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
console.log(docs);
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
return res.json(arr);
});
});
});
Also, for future use, do not reuse variable names in nested functions (you have 3 functions that use the variable err).
I have just made a simple program to display and insert data from a database(sql server 2008). My code does the display of data. I am unable to get data inserted. It shows no error in terminal or browser.
Here is my javascriptfile
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
var sql = require("mssql");
var config = {
user: 'pkp',
password: 'pkp',
server: 'PRAVEEN\\SQLEXPRESS',
database: 'myneww'
};
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
console.log(req.query.first_name);
var res=request.query('insert into Mytab values(req.query.first_name ,req.query.last_name)');
});
});
app.get('/alldata', function (req, res) {
sql.connect(config, 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 Mytab', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Here is my html file
<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
I am able to get the values displayed in the console, means values are passed and retrieved from the form. But still not inserted into the database.
I'm not good in javascript, but I guess the line below is incorrect:
var res=request.query('insert into Mytab values(req.query.first_name ,req.query.last_name)');
It should be something like this.
var res=request.query('insert into Mytab values(' + req.query.first_name + ',' + req.query.last_name +')');
If not, you've got an idea.
First, you were not passing values properly to query and, secondly, you are not waiting for the record to insert. Add the callback that I added.
app.get('/process_get', function (req, res) {
//some code
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
console.log(req.query.first_name);
request.query('insert into Mytab values('+req.query.first_name+','+req.query.last_name+')', function(err, recordset) {
if (err) {
console.log(err);
return res.send('Error occured');
}
return res.send('Successfully inserted');
});
});
});
Update
Use transaction to commit changes.
app.get('/process_get', function (req, res) {
//some code
var sqlConn = new sql.Connection(config);
sqlConn.connect().then(function () {
var transaction = new sql.Transaction(sqlConn);
transaction.begin().then(function () {
var request = new sql.Request(transaction);
request.query('Insert into EmployeeInfo (firstName,secondName) values ('+req.query.first_name+','+req.query.last_name+')').then(function () {
transaction.commit().then(function (recordSet) {
console.log(recordSet);
sqlConn.close();
return res.send('Inserted successfully');
}).catch(function (err) {
console.log("Error in Transaction Commit " + err);
sqlConn.close();
return res.send('Error');
});
});
});
});
Forgive me, if there is any typo.
I've got the following node/express code:
app.get("/notes/:categoryName", function (res, req) {
var categoryName = req.params.categoryName;
res.render("notes", {title: categoryName});
});
But when I look at req.params, it's undefined.
Yet, in another controller it works fine:
app.get("/api/notes/:categoryName", function (req, res) {
var categoryName = req.params.categoryName;
data.getNotes(categoryName, function (err, notes) {
if (err) {
res.send(400, err);
} else {
res.set("Content-Type", "application/json");
res.send(notes.notes);
}
});
});
What's the deal?
app.get("/notes/:categoryName", function (res, req) {
More attention :
app.get("/notes/:categoryName", function (req, res) {
You switched the params (res, req)
first i make a '/init' request and the response is {"x":50},
then i make a '/user' request and the response is {"x":50,"data":"jack"}. No problem so far, but if i make an init request again it makes a {"x":50,"data":"jack"} response again, how is this possible?
var resp.success = {"x":50}
exports.init = function (req, res) {
res.json(resp.success)
};
exports.user = function (req, res) {
User.findOne({_id: "1234"}).exec(function (err, user) {
var response = resp.success;
response.data = user.name;
res.json(response);
});
};
Because you've defined var resp.success = {"x":50} in a scope outside the #init and #user methods, when you modify/read the resp.success from within those methods, they are accessing a single shared object instance of resp.success. You can fix this by defining resp.success independently inside the #init method and #user:
exports.init = function (req, res) {
var resp.success = {"x":50}
res.json(resp.success)
};
exports.user = function (req, res) {
var resp.success = {"x":50}
User.findOne({_id: "1234"}).exec(function (err, user) {
var response = resp.success;
response.data = user.name;
res.json(response);
});
};
If you use the underscoreJS library, you could also do something like this:
var resp.success = {"x":50}
exports.init = function (req, res) {
var successResponseForThisRequest = _.clone(res.success);
res.json(resp.success)
};
exports.user = function (req, res) {
User.findOne({_id: "1234"}).exec(function (err, user) {
var successResponseForThisRequest = _.clone(res.success);
response.data = user.name;
res.json(response);
});
};