I have question about getting data form MongoDB with express. I can console.log the correct data, but i'm not able to render it as an .ejs file. It just gives me [object] instead of the actual data. Hope someone can help. I'm very new to express and mongoDB, so it's properly straight forward.
expressApp.get('/home', function(request, response) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("agile-app-db");
dbo.collection("Members").findOne({}, function(err, result) {
if (err) throw err;
console.log(result);
response.render('index', {'result' : result})
db.close();
});
});
});
EJS FILE
<ul>
<li><%= result %> </li>
</ul>
Please see Express and ejs <%= to render a JSON
<%- JSON.stringify(result) %>
Related
I was trying to pass my data from mongodb/express to react using componentDidMount() life cycle function but for some reason it doesn't work but instead it gives me this "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" error.
Here's how I set up my express:
app.get('/movies', function(req, res){
movie.find({}, function(err, allMovies){
if(err){
console.log(err);
} else {
res.send(allMovies);
}
})
});
app.listen(3000, function(){
console.log('App server is listening to 3000');
});
And inside my react file I call the componentDidMount function which is running via webpack at port 8080.
componentDidMount() {
console.log('test')
fetch('/movies')
.then(response => response.json())
.then(movies => this.setState({
movies: movies
}));
}
when i console.log response it returns this https://prnt.sc/iye6kk.
Any idea what am I doing wrong why my data is not passing properly?
In componentDidMount,script is parsing the response to JSON.
.then(response => response.json())
But server is not sending the response in the JSON format.
Send it in json format.
res.json({allMovies}); //ecma6 shorthand property names
Or
res.json({allMovies : allMovies});
I am sending my data like. I am new to angular. I am not able to access the userDetails in my post request.
Upload.upload({
url: '/api/upload/',
data: {'File': File, 'userDetails': userDetails}
});
Server Code:
userRouter.route('/upload')
.post(function(req, res) {
console.log(req.data);
upload(req, res, function(err) {
if(err) {
res.json({ error_code:1, err_desc:err });
return;
}
res.json({ error_code:0, err_desc:null });
})
});
the field req.data is undefined
I'm new on angularjs too and I had the same problem. I made use of https://github.com/expressjs/node-multiparty to get the data sent from ng-file-upload.
I hope it helps you too.
I am trying to make a range query and show the data in my ejs view
EJS View "historicos.ejs"
<h1>historicos</h1>
<form action="/historicos/buscar">
<input type="text" name='inicio' id='inicio'></li>
<input type="text" name='final' id='final'></li>
<br>
<button type="submit">Buscar</button>
</form>
<% if(typeof his !== 'undefined'){
his.forEach(function(dati){%>
<%= dati.temp %>
<%= dati.hum %>
<%= dati.date %>
<br/>
<%});
}; %>
I am using a controller with 2 methods, 1 for render the page and one to manage the query.
Controller "grafi.js"
var Si = require('../models/sis');
exports.getPagehis = function(req, res) {
if (req.user) return res.redirect('/');
res.render('historicos');
};
exports.getHis= function(req, res, next) {
ini = req.body.inicio;
fin = req.body.final;
console.log(ini)
console.log(fin)
Si.find({"date": {"$gte":ini, "$lt":fin}},function(err, his) {
console.log(his);
if(err) return next(err);
res.render('historicos', {
his:his
});
});
};
and this is my router file
router.get('/historicos', hiController.getPagehis);
router.get('/historicos/buscar', hiController.getHis);
if I write manually ini and fin to make the query(using this format YYYY-MM-DDThh:mm), I mean without the req.body.inicial and req.body.final, it work well but when I request the information from the view I got this fields undifined.
what can i do to solve this?
the problem was form and the request in general adding method="get" in the form and update the controller with:
var Url = require('url');
...
queryparams = Url.parse(req.url,true).query;
ini = queryparams.ini;
fi = queryparams.fi;
... make the query to mongo db
with this code is possible to get the values in the input files passed in the url
In order to insert the tweets in mongodb i wrote the below code
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Now i want to fetch the tweets from the mongodb and display to the browser. i am trying this since three day, can anyone help me .
I've got a simply form, that sends POST data to my Node.JS server, with Express. This is the form:
<form method="post" action="/sendmessage">
<div class="ui-widget">
<input type="text" id="search" data-provide="typeahead" placeholder="Search..." />
</div>
<textarea id="message"></textarea>
</form>
The ui-widget and the input is releated with typehead, an autocomplete library from Twitter.
And this is how I handle the POST request in the server:
app.post('/sendmessage', function (req, res){
console.log(req.body);
usermodel.findOne({ user: req.session.user }, function (err, auser){
if (err) throw err;
usermodel.findOne({ user: req.body.search }, function (err, user){
if (err) throw err;
var message = new messagemodel({
fromuser: auser._id,
touser: user._id,
message: req.body.message,
status: false
});
message.save(function (err){
if (err) throw err;
res.redirect('/messages')
})
});
});
});
The console shows me '{}', and then an error with req.body.search, because search is not defined. I don't know what is happening here, and it's not a problem related with the typehead input. Any solution for this problem...?
Thank's advance!
req.body is made up of names and values.
add name="search" on your search box and try again.
You also must use the express/connect.bodyParser() middleware, thanks Nick Mitchinson!
I had this problem and it turned out I was using app.use(express.bodyParser()); but it was after the code I was using. Moving it up solved the issue.
on express 4 would be this one. (note that this will not parse multipart/uploads).
app.use(bodyParser.urlencoded({extended: true}));
and if you want to receive json input
app.use(bodyParser.json());
In my case it was caused by my app redirecting http to https.
Updating Facebook to use the https uri fixed it.
In my case I did not provide name tags like this name="firstname" in my input field. After adding them, everything worked.