Express js routing error ("Cannot GET /") - javascript

I am having a hard time wondering why, when i access my HTTP server http://localhost:8000/, i get a "Cannot GET /" message. I use express js for routing server side and angular at client-side.
I have read that this error is there because i haven't set a route for "/" path, but i don't want to route anything there, just want to let my angular handle "/".
FYI, my express server is in a different path than the angular app.
MY node code:
var bcrypt = require('bcryptjs');
var bodyParser = require('body-parser');
var cors = require('cors');
var express = require('express');
var jwt = require('jwt-simple');
var moment = require('moment');
var mongoose = require('mongoose');
var path = require('path');
var request = require('request');
var compress = require('compression');
var config = require('./config');
var User = mongoose.model('User', new mongoose.Schema({
instagramId: { type: String, index: true },
email: { type: String, unique: true, lowercase: true },
password: { type: String, select: false },
username: String,
fullName: String,
picture: String,
accessToken: String
}));
mongoose.connect(config.db);
var app = express();
app.set('port', process.env.PORT || 8000);
app.use(compress());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 2628000000 }));
/*
|--------------------------------------------------------------------------
| Login Required Middleware
|--------------------------------------------------------------------------
*/
function isAuthenticated(req, res, next) {
if (!(req.headers && req.headers.authorization)) {
return res.status(400).send({ message: 'You did not provide a JSON Web Token in the Authorization header.' });
}
var header = req.headers.authorization.split(' ');
var token = header[1];
var payload = jwt.decode(token, config.tokenSecret);
var now = moment().unix();
if (now > payload.exp) {
return res.status(401).send({ message: 'Token has expired.' });
}
User.findById(payload.sub, function(err, user) {
if (!user) {
return res.status(400).send({ message: 'User no longer exists.' });
}
req.user = user;
next();
})
}
/*
|--------------------------------------------------------------------------
| Generate JSON Web Token
|--------------------------------------------------------------------------
*/
function createToken(user) {
var payload = {
exp: moment().add(14, 'days').unix(),
iat: moment().unix(),
sub: user._id
};
return jwt.encode(payload, config.tokenSecret);
}
/*
|--------------------------------------------------------------------------
| Sign in with Email
|--------------------------------------------------------------------------
*/
app.post('/auth/login', function(req, res) {
User.findOne({ email: req.body.email }, '+password', function(err, user) {
if (!user) {
return res.status(401).send({ message: { email: 'Incorrect email' } });
}
bcrypt.compare(req.body.password, user.password, function(err, isMatch) {
if (!isMatch) {
return res.status(401).send({ message: { password: 'Incorrect password' } });
}
user = user.toObject();
delete user.password;
var token = createToken(user);
res.send({ token: token, user: user });
});
});
});
/*
|--------------------------------------------------------------------------
| Create Email and Password Account
|--------------------------------------------------------------------------
*/
app.post('/auth/signup', function(req, res) {
User.findOne({ email: req.body.email }, function(err, existingUser) {
if (existingUser) {
return res.status(409).send({ message: 'Email is already taken.' });
}
var user = new User({
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
user.password = hash;
user.save(function() {
var token = createToken(user);
res.send({ token: token, user: user });
});
});
});
});
});
/*
|--------------------------------------------------------------------------
| Sign in with Instagram
|--------------------------------------------------------------------------
*/
app.post('/auth/instagram', function(req, res) {
var accessTokenUrl = 'https://api.instagram.com/oauth/access_token';
var params = {
client_id: req.body.clientId,
redirect_uri: req.body.redirectUri,
client_secret: config.clientSecret,
code: req.body.code,
grant_type: 'authorization_code'
};
// Step 1. Exchange authorization code for access token.
request.post({ url: accessTokenUrl, form: params, json: true }, function(error, response, body) {
// Step 2a. Link user accounts.
if (req.headers.authorization) {
User.findOne({ instagramId: body.user.id }, function(err, existingUser) {
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, config.tokenSecret);
User.findById(payload.sub, '+password', function(err, localUser) {
if (!localUser) {
return res.status(400).send({ message: 'User not found.' });
}
// Merge two accounts. Instagram account takes precedence. Email account is deleted.
if (existingUser) {
existingUser.email = localUser.email;
existingUser.password = localUser.password;
localUser.remove();
existingUser.save(function() {
var token = createToken(existingUser);
return res.send({ token: token, user: existingUser });
});
} else {
// Link current email account with the Instagram profile information.
localUser.instagramId = body.user.id;
localUser.username = body.user.username;
localUser.fullName = body.user.full_name;
localUser.picture = body.user.profile_picture;
localUser.accessToken = body.access_token;
localUser.save(function() {
var token = createToken(localUser);
res.send({ token: token, user: localUser });
});
}
});
});
} else {
// Step 2b. Create a new user account or return an existing one.
User.findOne({ instagramId: body.user.id }, function(err, existingUser) {
if (existingUser) {
var token = createToken(existingUser);
return res.send({ token: token, user: existingUser });
}
var user = new User({
instagramId: body.user.id,
username: body.user.username,
fullName: body.user.full_name,
picture: body.user.profile_picture,
accessToken: body.access_token
});
user.save(function() {
var token = createToken(user);
res.send({ token: token, user: user });
});
});
}
});
});
app.get('/api/feed', isAuthenticated, function(req, res) {
var feedUrl = 'https://api.instagram.com/v1/users/self/feed';
var params = { access_token: req.user.accessToken };
request.get({ url: feedUrl, qs: params, json: true }, function(error, response, body) {
if (!error && response.statusCode == 200) {
res.send(body.data);
}
});
});
app.get('/api/media/:id', isAuthenticated, function(req, res) {
var mediaUrl = 'https://api.instagram.com/v1/media/' + req.params.id;
var params = { access_token: req.user.accessToken };
request.get({ url: mediaUrl, qs: params, json: true }, function(error, response, body) {
if (!error && response.statusCode == 200) {
res.send(body.data);
}
});
});
app.post('/api/like', isAuthenticated, function(req, res) {
var mediaId = req.body.mediaId;
var accessToken = { access_token: req.user.accessToken };
var likeUrl = 'https://api.instagram.com/v1/media/' + mediaId + '/likes';
request.post({ url: likeUrl, form: accessToken, json: true }, function(error, response, body) {
if (response.statusCode !== 200) {
return res.status(response.statusCode).send({
code: response.statusCode,
message: body.meta.error_message
});
}
res.status(200).end();
});
});
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});

In that case, then you should catch all the routes in / to angular.
Put this code at the very last of your route definitions before error handlers.
app.get('*', function (req, res) {
res.sendFile('/path/to/angular/index.html');
});

As you are using Angular for your web app, you would want your express server to serve all the files related to the front-end so when you land on the link "http://localhost:8000/", Express would serve the related files back. This folder would include .js, .css and .html files as well as all the other resources (images, videos etc.) so you can link them in your markup. (eg link href="/logo.png").
You can serve these files using Express by telling express to use the Static Middleware.
Using the Middleware, you would tell Express to serve the contents of a specific folder as static resources. Putting your Angular App in the folder would then let Angular handle the routes.
var publicFolder = path.join(__dirname, '../client')
app.use(express.static(publicFolder);
You would register other endpoints to create an API for your web app. So express server would be able to provide data to the Angular app through those endpoints.

Related

Node JS Express, Passport JS, and Android Device Authentication Issues

I am currently implementing a login page via Node JS Express and Passport using Passport's local strategy: http://www.passportjs.org/packages/passport-local/.
The database is using MongoDB.
The problem that is occurring is I am unable to login successfully (sometimes I can, but it is not consistent) on an android phone and android tablet with User A.
The response being returned is a 401 (unauthorized error).
I have verified that I can log in successfully consistently with User A from a desktop computer, and also verified I can login on iOS devices (iPhone and iPad).
Does anyone have any suggestions, and / or know what the issue is?
Below is the code that executes the authentication
app_api/config/passport.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var User = mongoose.model('User');
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy({
usernameField: 'email'
},
function(username, password, done) {
User.findOne({ email: username }, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, {
message: 'Incorrect username.'
});
}
if (!user.validPassword(password)) {
return done(null, false, {
message: 'Incorrect password.'
});
}
return done(null, user);
});
}
));
app_api/controllers/authentication.js
var passport = require('passport');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.test = function(req, res) {
sendJSONresponse(res, 200, { 'status' : 'success' });
};
module.exports.register = function(req, res) {
if(!req.body.name || !req.body.email || !req.body.password) {
sendJSONresponse(res, 400, {
"message": "All fields required"
});
return;
}
var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.setPassword(req.body.password);
user.setShowResume(false);
user.save(function(err) {
var token;
if (err) {
sendJSONresponse(res, 404, err);
} else {
token = user.generateJwt();
sendJSONresponse(res, 200, {
'token' : token
});
}
});
};
module.exports.login = function(req, res) {
if(!req.body.email || !req.body.password) {
sendJSONresponse(res, 400, {
'message': 'All fields required'
});
return;
}
passport.authenticate('local', function(err, user, info){
var token, showResume;
if (err) {
sendJSONresponse(res, 404, err);
return;
}
if(user){
token = user.generateJwt();
showResume = user.showResume;
sendJSONresponse(res, 200, {
'token' : token,
'showresume': showResume
});
} else {
sendJSONresponse(res, 401, info);
}
})(req, res);
};
module.exports.logout = function(req, res) {
req.logout();
res.redirect('/');
};
Below is the controller app_server/controllers/index.js and the function logincontinue which calls the app_api/controllers/authentication.js file and its function login:
app_server/controllers/index.js
var request = require('request');
var apiOptions = {
server : "http://localhost:3000"
};
if (process.env.NODE_ENV === 'production') {
apiOptions.server = "https://siteDomain.com";
}
module.exports.home = function(req, res) {
renderLoginPage(req, res);
};
/* Other routes / functions ... */
module.exports.logincontinue = function(req, res) {
var path = '/api/authentication/login', sess;
//var connectSid = res.req.cookies['connect.sid'];
var requestOptions = {
url : apiOptions.server + path,
method : "POST",
json : { email: req.body.username, password: req.body.password }/*,
headers : { 'set-cookie': connectSid }*/
};
request(requestOptions, function(err, response, body) {
if(err) {
renderPage(req, res, 'siteDomain.com', 'loginerror');
} else if(response.statusCode === 200) {
switch(body.showresume) {
case true:
res.render('loginsuccessresume', { title: 'siteDomain.com', page: 'loginsuccessresume', showresume: true });
break;
default:
renderPage(req, res, 'siteDomain.com', 'loginsuccess');
break;
}
} else if(response.statusCode === 401) {
res.render('loginunauthorized', { title: 'siteDomain.com', page: 'loginunauthorized', errormessage: body.message });
} else {
renderPage(req, res, 'siteDomain.com', 'loginerror');
}
});
};
var renderPage = function(req, res, titleValue, pageValue) {
res.render(pageValue, { title: titleValue, page: pageValue });
};
var renderLoginPage = function(req, res) {
res.render('index', { title: 'siteDomain.com', page: 'login' });
};
As an update, this issue has been resolved.
The issue was related to case-sensitivity with respect to the username field.
Changing req.body.username to req.body.username.toLowerCase() resolved the issue within app_server/controllers/index.js and the function logincontinue.
Thank you.

Unable to use the Request Body from POST

I'm trying to develop api with node.js express api for my angular web front end.This code worked when I used the params (http://localhost:5000/login/admin/00606006350066500673 ).
But I don't know why I'm getting an error while using the Request raw body data ({ strUserID: "admin" , strUserPwd: "00606006350066500673"})
router.post('/login', function (req, res, next) {
let User = {
strUserID : req.body.strUserID,
strUserPwd : req.body.strUserPwd };
function getUserPwd(strUID){
var sqlConfig = {
user: 'sa',
password: 'XXXXX',
server: 'XXXXXXXXXXXXXX.us-east-2.rds.amazonaws.com',
database: 'XXXXX'
};
sql.connect(sqlConfig, function () {
var request = new sql.Request();
var strquery = "select fUserPwd from tblUser where fUserID ='"+User.strUserID+"'"
request.query(strquery, function (err, recordset) {
return(recordset);
});
sql.close();
});
}
if ( User.strUserPwd == getUserPwd(User.strUserID)) {
let token = jwt.sign(User, global.config.secretKey, {
algorithm: global.config.algorithm,
expiresIn: '15m'
});
console.log("Token Generated : "+ token + User );
res.status(200).json({
token , User
});
}
else {
res.status(401).json({
message: 'Login Failed'
});
}
});

jsonwebtoken doesn't retrieve a token

I am using nodejs and sequelize to create simple user registration, I already did the login and register, but when login is a success I don't get any token.
I have tried to console.log the token to see if I get some result, but there is no response in the console related to the token.
Here is my code:
var express = require('express');
var User = require('../../models').User;
var router = express.Router();
var jwt = require('jsonwebtoken');
var app = require('../../app');
/*var token = jwt.sign(user, app.get('superSecret'), {
expiresInMinutes: 1440 // expires in 24 hours
});*/
router.post('/', function (req, res, next) {
if (JSON.stringify(req.body) == "{}") {
return res.status(400).json({ Error: "Login request body is empty" });
}
if (!req.body.username || !req.body.password) {
return res.status(400).json({ Error: "Missing fields for login" });
}
// search a user to login
User.findOne({ where: { username: req.body.username} }) // searching a user with the same username and password sended in req.body
.then(function (user) {
if (user && user.validPassword(req.body.password)) {
//return res.status(200).json({ message: "loged in!" }); // username and password match
// create a token
var token = jwt.sign(user, app.get('superSecret'), {
expiresInMinutes: 1440 // expires in 24 hours
});
// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
else{
return res.status(401).json({ message: "Unauthorized" }); // if there is no user with specific fields send
}
}).catch(function (err) {
return res.status(500).json({ message: "server issues when trying to login!" }); // server problems
});
});
module.exports = router;
You should use express-jwt library. https://www.npmjs.com/package/express-jwt
It's middleware for express. Example:
var jwt = require('express-jwt');
app.get('/protected',
jwt({secret: 'shhhhhhared-secret',
credentialsRequired: false,
getToken: (req) => req.cookies.id_token // when cookies are using. 'id_token' is cookie's name
}),
function(req, res) {
if (!req.user.admin) return res.sendStatus(401);
res.sendStatus(200);
});
Also you may write as app.use(...) or app.anyRequest(...)

Error: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup

I am currently implementing a Google login and Google calendar implementation and testing out a function when a Google user logs in it pulls their events and prints to the console. however, I am getting the following error in the console
Error: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.
and when I console.log the calendar, it gives me a null.
I have made sure Google+ API and Google calendar API are both enabled in the console as well.
I am new to web development in general, I followed a tutorial to get me started and began trying to use the Google API's. I am using the MEAN stack for this project. Here is the relevant code.
var FacebookStrategy = require('passport-facebook').Strategy;
var User = require('../models/user');
var session = require('express-session');
var jwt = require('jsonwebtoken');
var secret = 'check123';
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var gcal = require('google-calendar');
var google = require('googleapis');
module.exports = function(app,passport, auth) {
app.use(passport.initialize());
app.use(passport.session());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
passport.serializeUser(function(user, done) {
token = jwt.sign({ username: user.username, email: user.email }, secret, {expiresIn: '24h'});
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new FacebookStrategy({
clientID: '422080801499546',
clientSecret: '34f91021248106dea49daa111bb7ff89',
callbackURL: "http://localhost:8000/auth/facebook/callback",
profileFields: ['id', 'displayName', 'photos', 'email']
},
function(accessToken, refreshToken, profile, done) {
console.log(profile._json.email);
User.findOne({ email: profile._json.email }).select('username password email').exec(function(err, user){
if(err) done(err);
if (user && user !== null) {
done(null, user);
} else {
done(err);
}
});
//done(null, profile);
}
));
// Use the GoogleStrategy within Passport.
// Strategies in Passport require a `verify` function, which accept
// credentials (in this case, an accessToken, refreshToken, and Google
// profile), and invoke a callback with a user object.
passport.use(new GoogleStrategy({
clientID: '655984940226-ob15jvq3hvqha4969tlb3oco9tun1i9t.apps.googleusercontent.com',
clientSecret: 'hsZtBDsfiCvdPz0gT-tqdUZ_',
callbackURL: "https://frozen-woodland-75947.herokuapp.com/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOne({ email: profile.emails[0].value }).select('username password email').exec(function(err, user){
if(err) done(err);
if (user && user !== null) {
done(null, user);
} else {
done(err);
}
});
var google_calendar = google.calendar('v3');
console.log('im here');
google_calendar.events.list({
auth: auth,
calendarId: 'primary',
timeMin: (new Date()).toISOString(),
singleEvents: true,
orderBy: 'startTime'
}, function(err, calendarList){
console.log(calendarList);
if(err){
console.log('bad list: ' + err);
return;
}
var events = calendarList.items;
if(events.length ==0){
console.log('No items found');
} else {
console.log('Upcoming events:');
console.log('%s -%s', start, event.summary);
}
})
}
Next is my authentication functions, my api.js:
var User = require('../models/user');
var jwt = require('jsonwebtoken');
var secret = 'check123';
module.exports = function(router){
//USER REGISTRATION
router.post('/users', function(req, res){
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.email = req.body.email;
if(req.body.username == null || req.body.username == ''|| req.body.password == null || req.body.email == null || req.body.password == '' || req.body.email == ''){
res.json({ success: false, message: 'Ensure username, email, and password were provided'}); //false if the route is null empty etc.
} else {
user.save(function(err){
if(err) {
res.json({success: false, message: 'Username or email already exists'});
} else {
res.json({success: true, message: 'user created!'});
}
});
}
});
//USER LOGIN ROUTE
//http://localhost:port/api/authenticate
router.post('/authenticate', function(req,res){
User.findOne({ username: req.body.username }).select('email username password').exec(function(err,user){
if(err) throw err;
if(!user){
res.json({success: false, message: 'Could not authenticate user'});
} else if (user) {
if( req.body.password) {
var validPassword = user.comparePassword(req.body.password);
} else {
res.json({success: false, message: 'No password Provided'});
}
if(!validPassword) {
res.json({ success: false, message: ' Could not Authenticate password'});
} else {
var token = jwt.sign({ username: user.username, email: user.email }, secret, {expiresIn: '24h'}); // create json token when they successfully log in with secret encryption and expires in 24 hours
res.json({ success: true, message: ' User Authenticated!', token: token}); // respond to user with that token
}
}
});
});
router.use(function(req, res, next){
var token = req.body.token || req.body.query || req.headers['x-access-token'];
console.log(token);
if(token) {
//varify token
jwt.verify(token,secret,function(err,decoded){
if(err) {
res.json({success: false, message: 'Token invalid'});
} else {
req.decoded = decoded; //decrpyts token - user/email
next();
}
});
}else {
res.json({success: false, message: 'No token provided'});
}
});
router.post('/me', function(req, res) {
res.send(req.decoded);
});
return router;
}
Login controllers:
//controls main index - runs when main page loads
angular.module('mainController', ['authServices'])
.controller('mainCtrl', function(Auth,$timeout, $location,$rootScope, $window){
var app = this; // so we can access outside of scoper
app.loadme = false;
$rootScope.$on('$routeChangeStart', function() {
if(Auth.isLoggedIn()) {
app.isLoggedIn = true;
Auth.getUser().then(function(data){
app.username = data.data.username;
app.useremail = data.data.email;
app.loadme = true;
});
} else {
app.isLoggedIn = false;
app.username = '';
app.loadme = true;
}
});
this.google = function() {
$window.location = $window.location.protocol + '//' + $window.location.host + '/auth/google';
};
this.doLogin = function(loginData) { //when the register button is pressed controller
app.loading = true;
app.errorMsg = false;
Auth.login(app.loginData).then(function(data){
if(data.data.success){
app.loading = false;
app.successMsg = data.data.message + '...redirecting';
$timeout(function() {
$location.path('/about');
app.loginData = '';
app.successMsg = false;
}, 2000);
} else {
app.loading = false;
app.errorMsg = data.data.message;
}
});
};
this.logout = function() {
Auth.logout();
$location.path('/logout');
$timeout(function(){
$location.path('/');
}, 2000);
};
})

Unit-test login with passport.js and express.js

I'm trying to test my local-login. I've implemented with passport.js, following its guide and following this MEAN skeleton.
I'm pretty sure that the implementation is fine, but there is something wrong with the test that always fails authentication.
If authentication fails it should be redirect to "/signin"if authentication is correct it should be go to "/"
But when I test, the authentication always fails.
This is routes.js:
module.exports = function(app, passport, auth) {
var users = require('../app/controllers/users');
app.get('/signin', users.signin);
app.post('/users/session', passport.authenticate('local', {
failureRedirect: '/signin',
failureFlash: 'Invalid email or password.'
}), users.session);
var index = require('../app/controllers/index');
app.get('/', index.render);
passport.js:
var mongoose = require('mongoose'),
LocalStrategy = require('passport-local').Strategy,
User = mongoose.model('User'),
config = require('./config');
module.exports = function(passport) {
//Serialize sessions
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findOne({
_id: id
}, '-salt -hashed_password', function(err, user) {
done(err, user);
});
});
//Use local strategy
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(email, password, done) {
User.findOne({
email: email
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'Unknown user'
});
}
if (!user.authenticate(password)) {
return done(null, false, {
message: 'Invalid password'
});
}
return done(null, user);
});
}
));
}
and test: api.js:
var User, app, mongoose, request, server, should, user;
should = require("should");
app = require("../server");
mongoose = require("mongoose");
User = mongoose.model("User");
request = require("supertest");
server = request.agent("http://localhost:3000");
describe("<Unit Test>", function() {
return describe("API User:", function() {
before(function(done) {
user = new User({
email : "user#user.com",
firstName: "Full Name",
lastName : "Last Name",
password : "pass11"
});
user.save();
return done();
});
describe("Authentication", function() {
return it("Local login", function(done) {
return server.post("/users/session").send({
email : "user#user.com",
password: "pass11"
}).end(function(err, res) {
res.headers.location.should.have.equal("/");
return done();
});
});
});
return after(function(done) {
User.remove().exec();
return done();
});
});
});
This is what the terminal displays:
<Unit Test>
API User:
Authentication
1) Local login
0 passing (24ms)
1 failing
1) <Unit Test> API User: Authentication Local login:
actual expected
/signin
I'm trying using this code and work as expected
var User, app, mongoose, request, server, should, user, agent;
should = require("should");
app = require("../server");
mongoose = require("mongoose");
User = mongoose.model("User");
request = require("supertest");
agent = request.agent(app)
describe('User', function () {
before(function(done) {
user = new User({
email : "user#user.com",
firstName: "Full Name",
lastName : "Last Name",
password : "pass11"
});
user.save(done)
});
describe('Login test', function () {
it('should redirect to /', function (done) {
agent
.post('/users/session')
.field('email', 'user#user.com')
.field('password', 'pass11')
.expect('Location','/')
.end(done)
})
after(function(done) {
User.remove().exec();
return done();
});
})
})
for more reference check this test-user
here my screenshot

Categories

Resources