How to Post/Get with body in Swift - node.js

Im trying to connect to an api I made with node.js but it looks like there isn't a clear way to do it if there requires a body in the request. Im able to connect to it with postman on localhost because there i can set the params in the body but when i use the heroku url it throws an error. I read that apple made it so swift can no longer make requests with a body anymore. In another project i was able to successfully connect to an api made with python but instead of passing the data to the body it was passed as params. How can I change the api/swift code to accept the data as params in swift instead of the body?
Heres the function call in swift:
func logoin() {
let params: Parameters = [
"email" : "test#email.com",
"password" : "1234"
]
AF.request("https://app_name.herokuapp.com/user/login", method: .post, parameters: params, encoding: JSONEncoding.default, headers: ["Content-Type": "application/json"]).responseJSON { response in
if let error = response.error {
print(error)
}
else{
let jsonData = try! JSON(data: response.data!)
print("json data", response)
}
}
}
Heres the api in node.js
const User = require('../models/user')
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
exports.get_user = (req, res, next) => {
const id = req.params.userId;
User.findById(id)
.exec()
.then(doc => {
console.log('From database', doc);
if (doc) {
res.status(200).json(doc);
}
else {
res.status(404).json({ message: 'No valid entry found for user ID.' });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};
exports.user_login = (req, res, next) => {
User.find({ email: req.body.email }).exec().then(users => {
if (users.length < 1) {
return res.status(401).json({
message: 'Auth failed1'
});
}
bcrypt.compare(req.body.password, users[0].password, (err, result) => {
if (err) {
return res.status(401).json({
message: 'Auth failed2'
});
}
if (result) {
const token = jwt.sign({
email: users[0].email,
userId: users[0]._id
}, process.env.JWT_KEY)
return res.status(200).json({
message: 'Auth successful',
token: token
});
}
res.status(401).json({
message: 'Auth failed3'
});
});
}).catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.delete_user = (req, res, next) => {
User.deleteOne({ _id: req.params.userId })
.exec()
.then(result => {
res.status(200).json({
message: 'User deleted'
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.update_user = (req, res, next) => {
const id = req.params.userId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
User.updateOne({ _id: id }, { $set: updateOps })
.exec()
.then(result => {
console.log(result);
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.signup = (req, res, next) => {
User.find({ email: req.body.email }).exec().then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: 'User already exists'
});
}
else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
}
else {
const user = new User({
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result)
res.status(201).json({
message: 'Successfully created user'
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
})
}
})
}
}).catch();
};

Related

keeps getting "Illegal arguments: undefined, string at Object.bcrypt.hashSync"

I've been struggling with Bcrypt on my MERN project I'm trying to create an authentication system I'm trying to run tests on Postman and I'm not sure why do I keep getting the error: "Illegal arguments: undefined, string at Object.bcrypt.hashSync"
this is my postman request:
this is the Controller Code:
const config = require("../config/auth.config");
const db = require("../models");
const User = db.user;
const Role = db.role;
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
exports.signup = (req, res) => {
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
});
user.save((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (req.body.roles) {
Role.find(
{
name: { $in: req.body.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = roles.map((role) => role._id);
user.save((err) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
}
);
} else {
Role.findOne({ name: "user" }, (err, role) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = [role._id];
user.save((err) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
});
}
});
};
exports.signin = (req, res) => {
User.findOne({
username: req.body.username,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({ message: "Invalid Password!" });
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
req.session.token = token;
res.status(200).send({
id: user._id,
username: user.username,
email: user.email,
roles: authorities,
});
});
};
exports.signout = async (req, res) => {
try {
req.session = null;
return res.status(200).send({ message: "You've been signed out!" });
} catch (err) {
this.next(err);
}
};
The error message:
Illegal arguments: undefined, string at Object.bcrypt.hashSync wants to say that you're passing undefined as an argument to the hashSync function. We need to fix this error.
Take a closer look at this line where the error occurs:
password: bcrypt.hashSync(req.body.password, 8),
req.body.password is undefined, you can verify it by console.log(req.body.password). What's wrong is that you are sending data as URL parameters. So req.body is an empty object and req.body.password is undefined.
In Postman, select the Body tab, choose JSON format, then type your data as a JSON object. Then, in your code, use express.json() middleware to parse requests in JSON format. You'll have the desired output.
You can see my example request in Postman below:

Am I sending JWT token correctly and is it being received and stored correctly? NodeJS backend & React frontend

I am very new to both nodeJS and React, and am currently trying to get my head around user authentication. I am able to register new users and login to my backend via postman/rapid api, but cannot login correctly via my react front end. Code below:
Front End Requests
import axios from 'axios'
import {AuthModel, UserModel} from './_models'
const API_URL = process.env.REACT_APP_API_URL
export const GET_USER_BY_ACCESSTOKEN_URL = `${API_URL}/auth/signin`
export const LOGIN_URL = `${API_URL}/auth/signin`
export const REGISTER_URL = `${API_URL}/auth/signup`
export const REQUEST_PASSWORD_URL = `${API_URL}/forgot_password`
// Server should return AuthModel
export function login(email: string, password: string) {
return axios.post<AuthModel>(LOGIN_URL, {
email,
password,
})
}
// Server should return AuthModel
export function register(
email: string,
firstname: string,
lastname: string,
password: string,
password_confirmation: string
) {
return axios.post(REGISTER_URL, {
email,
firstname: firstname,
lastname: lastname,
password,
password_confirmation,
})
}
// Server should return object => { result: boolean } (Is Email in DB)
export function requestPassword(email: string) {
return axios.post<{result: boolean}>(REQUEST_PASSWORD_URL, {
email,
})
}
export function getUserByToken(token: string) {
return axios.post<UserModel>(GET_USER_BY_ACCESSTOKEN_URL, {
api_token: token,
})
}
Backend:
const jwt = require("jsonwebtoken");
const config = require("../config/auth.config.js");
const db = require("../models");
const User = db.user;
const Role = db.role;
verifyToken = (req, res, next) => {
let token = req.session.token;
if (!token) {
return res.status(403).send({ message: "No token provided!" });
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "Unauthorized!" });
}
req.userId = decoded.id;
next();
});
};
isAdmin = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "admin") {
next();
return;
}
}
res.status(403).send({ message: "Require Admin Role!" });
return;
}
);
});
};
isModerator = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "moderator") {
next();
return;
}
}
res.status(403).send({ message: "Require Moderator Role!" });
return;
}
);
});
};
const authJwt = {
verifyToken,
isAdmin,
isModerator,
};
module.exports = authJwt;
const config = require("../config/auth.config");
const db = require("../models");
const User = db.user;
const Role = db.role;
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
exports.signup = (req, res) => {
const user = new User({
username: req.body.email,
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
});
user.save((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (req.body.roles) {
Role.find(
{
name: { $in: req.body.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = roles.map((role) => role._id);
user.save((err,data) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({message: "User registered successfully?"});
});
}
);
} else {
Role.findOne({ name: "user" }, (err, role) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = [role._id];
user.save((err,data) => {
if (err) {
res.status(500).send({ message: err });
return;
}
var token = jwt.sign({ id: data._id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
// This is what I mean
req.session.token = token;
res.status(200).send({
id: user._id,
username: user.username,
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
});
//res.send({message: "User registered successfully? No 2"});
});
});
}
});
};
exports.signin = (req, res) => {
User.findOne({
username: req.body.email,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({ message: "Invalid Password!" });
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
req.session.token = token;
res.status(200).send({
id: user._id,
username: user.username,
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
roles: authorities,
});
});
};
exports.signout = async (req, res) => {
try {
req.session = null;
return res.status(200).send({ message: "You've been signed out!" });
} catch (err) {
this.next(err);
}
};
exports.allAccess = (req, res) => {
res.status(200).send("Public Content.");
};
exports.userBoard = (req, res) => {
res.status(200).send("User Content.");
};
exports.adminBoard = (req, res) => {
res.status(200).send("Admin Content.");
};
exports.moderatorBoard = (req, res) => {
res.status(200).send("Moderator Content.");
};
Any guidance would be greatly appreciated!

Not getting correct status code (409) if email exists using Next.js, Mongoose, MongoDb Atlas and Express

I am building a login/Register portion of my app. Right now I'm using express-validator to check if an email exists in my collection.
This is my route:
var router = require('express').Router()
var UserModel = require('../models/UserModel')
var { body } = require('express-validator');
router
.route('/registration')
.get(function(req, res) {
console.log(0)
UserModel.find({}, (err, users) => {
console.log(1);
if (err) return res.status(500).send(err)
console.log(2);
return res.json(users);
})
})
.post(body('username_email').custom(value => {
console.log("value ", value);
console.log(3)
UserModel.findOne({ 'username_email': value }, (err) => {
console.log(4);
if (err) return res.status(409).send(err);
})
}), async(req, res, next) => {
console.log(5)
try {
let newUser = new UserModel(req.body);
let savedUser = await newUser.save();
console.log(6);
if (savedUser) return res.redirect('/users/registration?success=true');
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
module.exports = router
In my component on the front end I have a function in my fetch which will catch the error if there is one.
handleErrors(response) {
if (!response.ok) {
console.log('This email exists!')
throw Error(response.statusText);
}
return response;
}
handleSubmit(event) {
event.preventDefault()
var { username, password } = this.state
var mailFormat = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
var error = false
if (!username.match(mailFormat)) {
this.setState({ usernameError: true })
error = true
} else {
this.setState({ usernameError: false })
}
if (password.length <= 8) {
this.setState({ passwordError: true })
error = true
} else {
this.setState({ passwordError: false })
}
console.log(`error ${error}`)
if (error == false) {
this.setState({ formError: false, formSuccess: true })
}
window.fetch('http://localhost:8016/users/registration', {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({ username_email: username, password: password })
})
.then(this.handleErrors)
.then(function (response) {
console.log(`response ${response}`)
return response.json()
}).then(function (data) {
console.log('User created:', data)
}).catch(function (error) {
console.log(error);
});
}
The console.log in the fetch, handleErrors is being registered in the console, but why isn't the error status a 409 like I indicated.
Closer excerpt of post route!
.post(body('username_email').custom(value => {
console.log("value ", value);
console.log(3)
Is this the problem? Node style should have a error and callback?
UserModel.findOne({ 'username_email': value }, (err) => {
console.log(4);
if (err) return res.status(409).send(err);
})
}), async(req, res, next) => {
console.log(5)
try {
let newUser = new UserModel(req.body);
let savedUser = await newUser.save();
console.log(6);
if (savedUser) return res.redirect('/users/registration?success=true');
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
UPDATE
I tried Nick's solution but I get this:
MongoError: E11000 duplicate key error collection: development.users index: email_1 dup key: { : null }
at Function.create (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb-core/lib/error.js:43:12)
at toError (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb/lib/utils.js:149:22)
at coll.s.topology.insert (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb/lib/operations/collection_ops.js:859:39)
at handler (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb-core/lib/topologies/replset.js:1155:22)
at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb-core/lib/connection/pool.js:397:18
at process._tickCallback (internal/process/next_tick.js:61:11)
POST /users/registration 500 312.485 ms - 51
^C
Two things I am noticing:
I get back MongoError: E11000 duplicate key error collection: development.users index: email_1 dup key: { : null }
which is the error from having a duplicate email, but number one where is E-mail already in use message in the console from the promise? And two how can I pass the error status "res.status(409).send(err);" from the promise?
The issue was that during your validation, you weren't returning the promise since the mongoose call is async. The rest the code ran before your validator was finished. I commented where you were missing the return.
router.route('/registration')
.get(function(req, res) {
UserModel.find({}, (err, users) => {
if (err) res.status(500).send(err)
res.json(users)
})
})
.post(body('username').custom(value => {
return UserModel.findOne({ 'email': value }).then(user => { // Return Promise
if (user) {
return Promise.reject('E-mail already in use');
}
});
}), async(req, res, next) => {
try {
let newUser = new UserModel(req.body)
let savedUser = await newUser.save(err => {
if (err) return res.json({ success: false, error: err })
return res.json({ success: true })
})
if (savedUser) return res.redirect('/users/registration?success=true');
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
module.exports = router
UPDATE
Just read through express-validator docs. I think you would need to validate the errors during the request process
var router = require('express').Router()
var UserModel = require('../models/UserModel')
var { body, validationResult } = require('express-validator');
router.route('/registration')
.get(function(req, res) {
UserModel.find({}, (err, users) => {
if (err) res.status(500).send(err)
res.json(users)
})
})
.post(body('username').custom(value => {
return UserModel.findOne({ 'email': value }).then(user => { // Return Promise
if (user) {
return Promise.reject('E-mail already in use');
}
});
}), async(req, res, next) => {
// Checks for errors in validation
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
try {
let newUser = new UserModel(req.body)
let savedUser = await newUser.save(err => {
if (err) return res.json({ success: false, error: err })
return res.json({ success: true })
})
if (savedUser) return res.redirect('/users/registration?success=true');
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
module.exports = router

Node.js UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent

I'm new to node.js and want to send out dataof User and Match in a single response by querying mongodb twice .
router.get('/preview/', checkAuth, (req, res)=> {
const errors = {};
const match = {}
User.findOne({_id: req.user.id})
.then(user => {
if (!user) {
return res.status(404).json({errors: 'Could not find a user' });
}
Match.findOne({ user: req.user.id }).then(m => {
console.log('match found!');
match = m;
}).catch(err=> res.status(404).json(err)); // <-error occures here
res.status(200).json({user, match});
})
.catch(err=> res.status(404).json(err));
});
But I get this error:
(node:8056) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
How can I fix it?
Please have a look at the comments added in your code.
router.get('/preview/', checkAuth, (req, res)=> {
const errors = {};
const match = {}
User.findOne({_id: req.user.id})
.then(user => {
if (!user) {
return res.status(404).json({errors: 'Could not find a user' });
}
Match.findOne({ user: req.user.id }).then(m => {
console.log('match found!');
match = m;
}).catch(err=> res.status(404).json(err)); // <-error occures here because you sent the response if error occurs
res.status(200).json({user, match}); // this will be executed even if there is an error so it will again try to send the response
})
.catch(err=> res.status(404).json(err));
});
Improved code:
router.get('/preview/', checkAuth, (req, res) => {
const errors = {};
User.findOne({ _id: req.user.id })
.then((user) => {
if (!user) {
return res.status(404).json({ errors: 'Could not find a user' });
}
Match.findOne({ user: req.user.id })
.then((m) => {
console.log('match found!');
res.status(200).json({ user, m }); // send the success response when the match found
})
.catch((err) => res.status(404).json(err)); // send the error response when erro thrown
})
.catch((err) => res.status(404).json(err));
});

JSON Web Tokens resetting express server

I'm creating a demo MEAN app and everything was going well I could Add and Authenticate Users and Add, Delete and Update Messages but after I implemented web token I can only view and delete messages when I try to add a new message I get this error.
The message is still added to my mongodb database but it stops the server.
I was trying to add my code from the components but I'm not allowed as I get a message saying that my post is mostly code and I need to add more information.
zone.js?fad3:2935 POST http://localhost:3000/message?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp7Il9pZCI6IjVhNWRiMmFjYmVkMWQ3MmZmOGQzMDM3YSIsImZpcnN0TmFtZSI6IkpvaG4iLCJsYXN0TmFtZSI6IkRvZSIsInBhc3N3b3JkIjoiJDJhJDEwJHZmMVQ2S0VCeVZBSE9qSkRyQWg0WC51N3NHYXZZVXNQSHZyOHFNTllydVdJL3lZZXBKR0ZhIiwiZW1haWwiOiJqb2huQGRvZS5jb20iLCJfX3YiOjksIm1lc3NhZ2VzIjpbXX0sImlhdCI6MTUxNjEwMjM1NSwiZXhwIjoxNTE2MTA5NTU1fQ.6Kj1TcprqWRQIAZ9GSDHLxIbf_9DzPhx5qomv6QtxfA net::ERR_CONNECTION_RESET
Message Route
let express = require('express');
let router = express.Router();
let jwt = require('jsonwebtoken');
let User = require('../models/user');
let Message = require('../models/message');
router.get('/', (req, res, next) => {
Message.find()
.populate('user', 'firstName')
.exec( (err, messages) => {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Success',
obj: messages
});
});
});
router.use('/', (req, res, next) => {
jwt.verify(req.query.token, 'secret', (err, decoded) => {
if (err) {
return res.status(401).json({
title: 'Not Authenticated',
error: err
});
}
next();
})
});
router.post('/', (req, res, next) => {
let decoded = jwt.decode(req.query.token);
User.findById(decoded.user._id, (err, user) => {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
let message = new Message({
content: req.body.content,
user: user
});
message.save((err, result) => {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
user.messages.push(result);
user.save();
res.status(201).json({
message: 'Saved message',
obj: result
});
});
});
});
router.patch('/:id', (req, res, next) => {
let decoded = jwt.decode(req.query.token);
Message.findById(req.params.id, (err, message) => {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!message) {
return res.status(500).json({
title: 'No Message Found!',
error: {message: 'Message not found'}
});
}
if (message.user != decoded.user._id) {
return res.status(401).json({
title: 'Not Authenticated',
error: {message: 'Users do not match'}
});
}
message.content = req.body.content;
message.save((err, result) => {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Updated message',
obj: result
});
});
});
});
router.delete('/:id', (req, res, next) => {
let decoded = jwt.decode(req.query.token);
Message.findById(req.params.id, (err, message) => {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!message) {
return res.status(500).json({
title: 'No Message Found!',
error: {message: 'Message not found'}
});
}
if (message.user != decoded.user._id) {
return res.status(401).json({
title: 'Not Authenticated',
error: {message: 'Users do not match'}
});
}
message.remove((err, result) => {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Deleted message',
obj: result
});
});
});
});
module.exports = router;
Message Service
import { Http, Response, Headers } from "#angular/http";
import { Injectable, EventEmitter } from "#angular/core";
import 'rxjs/Rx';
import { Observable } from "rxjs";
import { Message } from "./message.model";
#Injectable()
export class MessageService {
private messages: Message[] = [];
messageIsEdit = new EventEmitter<Message>();
constructor(private http: Http) {
}
addMessage(message: Message) {
const body = JSON.stringify(message);
const headers = new Headers({'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.post('http://localhost:3000/message' + token, body, {headers: headers})
.map((response: Response) => {
const result = response.json();
const message = new Message(
result.obj.content,
result.obj.user.firstName,
result.obj._id,
result.obj.user._id);
this.messages.push(message);
return message;
})
.catch((error: Response) => Observable.throw(error.json()));
}
getMessages() {
return this.http.get('http://localhost:3000/message')
.map((response: Response) => {
const messages = response.json().obj;
let transformedMessages: Message[] = [];
for (let message of messages) {
transformedMessages.push(new Message(
message.content,
message.user.firstName,
message._id,
message.user._id)
);
}
this.messages = transformedMessages;
return transformedMessages;
})
.catch((error: Response) => Observable.throw(error.json()));
}
editMessage(message: Message) {
this.messageIsEdit.emit(message);
}
updateMessage(message: Message) {
const body = JSON.stringify(message);
const headers = new Headers({'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.patch('http://localhost:3000/message/' + message.messageId + token, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => Observable.throw(error.json()));
}
deleteMessage(message: Message) {
this.messages.splice(this.messages.indexOf(message), 1);
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.delete('http://localhost:3000/message/' + message.messageId + token)
.map((response: Response) => response.json())
.catch((error: Response) => Observable.throw(error.json()));
}
}

Resources