Not getting any response for save - express

Whenever I request on 8081/list_user there is no response. When I open localhost:8081 I get a response but not for localhost:8081/list_user.Both files are in the same folder is there any issues with that.Please check this issue what's problem in that.
// grab the things we need schema.js file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var userSchema = new Schema({
name: String,
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
console.log("Schema")
module.exports = User;
////////////Next file
var express = require('express');
var app = express();
var User = require('./schema');
// This responds with "Hello World" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage",User);
res.send('Hello GET');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
var newUser = User({
name: 'Peter Quill',
});
// save the user
newUser.save(function(err) {
if (err) throw err;
res.send('User created!');
console.log('User created!');
});
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/find', function(req, res) {
User.find({}, function(err, users) {
if (err) throw err;
// object of all the users
console.log(users);
res.send(users)
});
})
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)
})

When I tested .save function the way it was I couldn't even get an error message. What I did was add a connection with my local database (at schema file) to test properly.
mongoose.connect('mongodb://localhost/test');
In order to do this, first you have to certify that you have a local mongodb server running (or you could just connect to an online server), mongoose.connect receives my connection string as parameter ("test" is the database name, if it doesn't exist it will be created automatically). Last thing I did was add new when I create an user.
var newUser = new User({
name: 'teste',
});

Related

How to access req.session in nextServerInit before rendering

I am setting up a website base on nuxt+express with cmd 'vue init nuxt-community/express-template'.The functionality i am working on is "auth".I am trying to get the session while i refresh the page so that to keep the store correctly(Just for user info).
After config the session(the middleware i use is 'express-session'), I set the session after 'login successfully' and console it correctly.However when i console the req.session in method nuxtServerInit, it gives me a 'undefined'.
// express-api
router.post('/login', async (req, res, next) => {
const { username, password } = req.body;
try {
const userQuery = await User.findOne({
username,
password: md5(password)
}).exec();
if (userQuery) {
req.session.user = userQuery
console.log(req.session)
return ResUtils.success(res, userQuery);
// store actions
nuxtServerInit({ commit }, { req, res }) {
console.log(req.session)
commit('initUserInfo', req.session.user)
I expect to get req.session.user with which i can initialize the store after refresh the page. unfortunately, req.session is undefined.
you need to add this in your server/index.js or server/app.js basically wherever you create your express instance
// Create express router
const router = express.Router()
// Transform req & res to have the same API as express
// So we can use res.status() & res.json()
router.use((req, res, next) => {
Object.setPrototypeOf(req, app.request)
Object.setPrototypeOf(res, app.response)
req.res = res
res.req = req
next()
})

Mongoose - FindOne() inside Multer

I am sending formData to my express app like so:
itemFactory.saveItem = function(item, callback){
var formData = new FormData();
for(var i = 0; i < item.photos.length; i++){
formData.append('photos', item.photos[i]);
}
for(var key in item){
formData.append(key, item[key])
}
return $http.post('/api/item/', formData, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(callback);
};
I am saving a new item to my mongoose DB. Now everything is working perfectly. But I want to detect duplicates using mongoose findOne(), and not just let mongoose handle detecting if a duplicate key exists when writing to the DB. Because my images get uploaded regardless at this stage, if a duplicate key exists or not. Because it only detects the duplicate on save()
The problem now, in my express app, is when I am using findOne(), Multer() has not yet decoded my formData. ex:
router.post('/item', function(req, res){
Vehicle.findOne({ id: String(req.body.id) }, function(error, item){
var storage = multer.diskStorage({...})
var upload = multer({
storage: storage
}).any();
upload(req, res, function(error){
//formData is only available here via req.body
//and not at findOne() stage.
});
});
});
I cannot do the findOne inside the upload because then the files would be uploaded anyway and then only detect a duplicate.
I tried another multer().any() function for getting the formData just after the .post() but that did not seem to work. I don't think I can do this:
var detectItem = multer().any()
detectItem(req, res, function(){
Vehicle.findOne({ id: String(req.body.id) }, function(error, item){
var storage = multer.diskStorage({...})
var upload = multer({
storage: storage
}).any();
upload(req, res, function(error){
//formData is only available here via req.body
//and not at findOne() stage.
});
})
It does not seem to like me using a multer function inside a multer function.
Any advice?
You can use fileFilter option to control which files are accepted.
It could be something like this:
function filFilter (req, file, cb) {
Vehicle
.findOne({ id: req.body.id })
.then(item => {
cb(null, !item); // Skip if item exists (passing false skips file)
})
}
You could separate them into two middlewares
app.post('/item', function(req, res, next){
//this middleware is used to check duplicate
Vehicle.findOne({id:req.body.id}).then(function(item){
if(item) res.end() //if item existed, send response directly
else next() //if item not existed, continue to next middleware
})
}, function(req, res){
var storage = multer.diskStorage({...})
var upload = multer({ storage: storage }).any();
upload(req, res, function(error){
// ...
});
})

How to explicitly pass user data to passport.authenticate

I'm making a webapp that uses Socket.io to pass information between the server and the client, one example being login information. The documentation for passport.authenticate says to use it like so:
app.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' }));
However, my webapp is using Polymer client-side routing, so the only route my index.js has is this:
app.get('*', function (req, res) {
res.sendFile('./public/index.html', {root: '.'});
});
Instead, I'd like to do something like this:
io.on('connection', function(socket){
socket.on('login', function(data){
passport.authenticate('local', data);
});
});
However, this doesn't work as the authenticate function doesn't even get called right now. Is there a way to make passport work in such a scenario?
You can try something like below .
In your routes define and require the socket module, so you have access to use it in routes.
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var router = express.Router();
var passport = require('passport');
io.on('connection', function(socket){
socket.on('login', function(data){
// call the routes
router.post('/login', function(request, response, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
// return next(err);
socket.emit('loginResult', { success: false });
}
if (!user) {
var message = "Invalid credentials";
socket.emit('loginResult', { success: false , message: message});
}
request.logIn(user, function (err) {
if (err) {
socket.emit('loginResult', { success: false });
}
// if want to save user in session
request.session.user = user;
// after success code
socket.emit('loginResult', { success: true , user : user});
});
})(request, response, next);
});
});
});
Hope this helps.
You can define your custom callback with passport.authenticate(). I have given a example below, you might wanna try that. Go here for more info.
io.on('connection', function(socket){
socket.on('login', function(data){
var req = {}
req.body = data
passport.authenticate('local', function(err, user, info) {
if (err) {
socket.emit('login', { success: false });
}
if (!user) {
socket.emit('login', { success: false });
}
// Set session
req.logIn(user, function(err) {
if (err) {
socket.emit('login', { success: false });
}
socket.emit('login', { success: true });
});
});
});
Update: Problem with previous code was, when using custom callbacks in passport authenticate it uses req object from the closure, which in this case was undefined as it was not in the router. I think, now that you can provide enough authentication data through req.body it should work.

socket emit an event on http PUT

I am using expressjs, nedb, and socket.io. Various (non-browser) clients are able to PUT new values into the db successfully. When that happens, I want a message emitted to all browsers connected to the server. I have the following code which is currently not sending a message back to the browser.
// on the server
//***************************************************************
// reachable to the world at http://server/foo
// clients can PUT data into the db
app.put('/foo', jsonParser, function(req, res, next) {
if (!req.body) return res.sendStatus(400);
db.insert(req.body, function (err, newDoc) {
io.sockets.emit('PUT a new value', { added: newDoc._id });
res.send('Success! Find it again with id: ' + newDoc._id);
});
});
// reachable to the world at http://server/
// browser shows a dashboard of events
app.get('/', function(req, res, next) {
// code to serve the dashboard here
});
io.sockets.on('connection', function (socket) {
socket.on('foo', function (data) {
io.sockets.emit('PUT a new value', data);
})
});
// in the browser
//***************************************************************
var socket = io.connect('/');
socket.on('PUT a new value', function (data) {
console.log(data);
});
Data get inserted into the db successfully from different non-browser clients, but the connected browser doesn't receive an update.
What am I doing wrong?
I found a solution which I don't like at all but it works. We can add io object to req or to res in the middleware like that:
app.use(function (req, res, next) {
req.io = io;
next();
});
before app.use('/', routes) and then in our router module we "import" the io object:
app.put('/foo', jsonParser, function(req, res, next) {
if (!req.body) return res.sendStatus(400);
db.insert(req.body, function (err, newDoc) {
var io = req.io; // HERE !!!
io.sockets.emit('PUT a new value', { added: newDoc._id });
res.send('Success! Find it again with id: ' + newDoc._id);
});
});
I know, I know... let's find something else :-)
I have the following app structure generated by express generator. I start the app with $ DEBUG=foo:* npm start
.
|____app.js
|____bin
| |____www
|____data
|____LICENSE
|____node_modules
|____package.json
|____public
| |____stylesheets
| |____javascripts
| |____images
|____README.md
|____routes
| |____index.js
| |____readings.js
| |____sensors.js
| |____users.js
|____views
| |____error.hjs
| |____index.hjs
In app.js
var express = require('express');
var app = express();
var io = require('socket.io')();
app.io = io;
// notice the `(io)` for the routes that need to be socket-aware
var routes = require('./routes/index');
var users = require('./routes/users');
var sensors = require('./routes/sensors');
var readings = require('./routes/readings')(io);
…
// start listening with socket.io
app.io.on('connection', function(socket){
console.log('a user connected');
});
module.exports = app;
Then in ./routes/readings.js
var express = require('express');
var app = express();
var router = express.Router();
module.exports = function(io) {
router.put('/', jsonParser, function(req, res, next) {
if (!req.body) return res.sendStatus(400);
db.insert(req.body, function (err, newDoc) {
io.emit("reading", {id: newDoc._id});
res.send('Success PUTting data! id: ' + newDoc._id);
});
});
return router;
}
Finally, in the index.hjs template for the client-side
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('reading', function (data) {
console.log(data);
});
</script>
The above works. When data are inserted into the db via an http PUT (see readings.js), an event is emitted by io.emit('reading', data) and the browser receives that event and shows it in the console with socket.on('reading', function (data) { … });

get current logged in user in Parse.com cloud code [duplicate]

When i use this function in Cloud Code Parse.User.current() return null.
I'm using parseExpressCookieSession for login.
Any advice?
var express = require('express');
var expressLayouts = require('cloud/express-layouts');
var parseExpressHttpsRedirect = require('parse-express-https-redirect');
var parseExpressCookieSession = require('parse-express-cookie-session');
// Required for initializing enter code hereExpress app in Cloud Code.
var app = express();
// Global app configuration section
app.set('views', 'cloud/views');
app.set('view engine', 'ejs'); // Switch to Jade by replacing ejs with jade here.
app.use(expressLayouts); // Use the layout engine for express
app.set('layout', 'layout');
app.use(parseExpressHttpsRedirect()); // Require user to be on HTTPS.
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('helloworld'));
app.use(parseExpressCookieSession({
fetchUser: true,
cookie: { maxAge: 3600000 * 24 }
}));
Parse.Cloud.beforeSave('Menu', function(request, response) {
var Business = Parse.Object.extend('Business');
var query = new Parse.Query(Business);
query.equalTo('profile', Parse.User.current().get('profile'));
query.find({
success: function(business) {
console.log(business);
response.success();
},
error: function(error) {
response.error(error.message);
}
});
});
app.listen();
This the code that i use to login/logout
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
// Login succeeded, redirect to homepage.
// parseExpressCookieSession will automatically set cookie.
res.redirect('/');
},
function(error) {
// Login failed, redirect back to login form.
res.redirect('/');
});
});
// Logs out the user
app.post('/logout', function(req, res) {
Parse.User.logOut();
res.redirect('/');
});
It is an old question but answering for future reference.
Parse.User.current() works in Javascript SDK when used in clients ex. WebApp where users log in and the you can fetch the current user with that function.
To get the user calling a Cloud Code function or doing an operation on an object (beforeSave,afterSave,beforeDelete and so on) you use the request.user property it contains the user issuing the request to Parse.com.
More details about Parse.Cloud.FunctionRequest here: https://parse.com/docs/js/api/classes/Parse.Cloud.FunctionRequest.html
Example code:
Parse.Cloud.beforeSave('Menu', function(request, response) {
var requestUser = request.user;
// instance of Parse.User object of the user calling .save() on an object of class "Menu"
// code cut for brevity
});