Variable route/url param connected to Mongodb - node.js

Thanks for reading my question!
I'm making a chat-app where people can chat with each other who are born at the same date.
So the question is,
How do I change the route with an additional birthdate which is changing with every different user with different birthdates?
I already can signup/login and save the birthdate for every user.
So I need to take the birthdate from the mongoDB to put it in the url so nobody gets directed to the wrong chat.
router.get("/", chatController.getAll);
app.use('/api/v1/chat', passport.authenticate('jwt', { session: false }), apiChatRouter);
const getAll = (req,res)=>{
Message.find({},(err,docs)=>{
if(!err){
res.json({
"status":"succes",
"data":{
"chat":docs
}
});
}
});
}
fetch('http://localhost:3000/api/v1/chat/', {
//nodige headers meegeven met localstorage
'headers':{
'Authorization': 'Bearer ' + localStorage.getItem('token')
}
}).then(result => {
return result.json();
}).then(json =>{
console.log(json);
}).catch(err =>{
console.log("Unauthorized")
});
If you want to check the rest of the code:
https://github.com/abuijzen/Herexamen-Webtech3

You can use express path param please check the below example
To redirect user to other path you can user
res.redirect('/1990-03-29');
to get param from url
app.get('/api/v1/chat/:bd', function (req, res) {
// http://localhost:xx/api/v1/chat/1990-03-29
req.params // eqal { "bd": "1990-03-29" }
})
Please check routing and redirect

Related

I want to check session data before an AJAX call in nodejs

In my shopping cart I want to check user session data before an ajax call.
If the user is not logged in I want them to redirected to login route. I have created a middleware called verifyLogin to check these login sessions for each time and it really works when not using an ajax. How can I add this middleware to my ajax function ?
Or please give me an another solution for this.
VerifyLogin Middleware
const verifyLogin = (req, res, next) => {
if (req.session.loggedIn) {
next()
} else {
res.redirect('/login')
}
}
Ajax function
function addToCart(proId) {
$.ajax({
url: '/add-to-cart/' + proId,
method: 'get',
success: (response) => {
if (response.status) {
let count = $('#cart-count').html()
count = parseInt(count) + 1
$("#cart-count").html(count)
}
}
})
}
Add to cart route of JS file
router.get('/add-to-cart/:id', (req, res) => {
userHelpers.addToCart(req.params.id, req.session.user._id).then(() => {
res.json({ status: true })
})
})
You can check the specified for session cookie-parameter by document.cookie is it set -- you are loggedin, else -- you are not logged in. Or, you can add extra cookie parameter that indicate if you successfully logged in. And this check you need to put before ajax call. Middleware layer will be working every time for any request to your server. But you need make check only if user trying to add something to cart, for example.

Add variable to a URL (node, express)

I'm using node and express. What I want to do is to do is make a mix of res.render and res.redirect.
Thing is, res.render can only receive a .ejs file and data, and redirect will go to a specific URL. What I need to do is go to a specific URL (e.g. /reviews/new/:id), render a .ejs file and give some data to it.
This is my code. I can't use session or cookies for this project.
This are the routes, user enters to edit a review of some show. If it is a new review, the id of the show is in the URL, if the user is editing one, the ID of the review is on the URL. Either way, if something fails, I have to append something to this URL and send data.
router.get('/new/:id', controller.newReview);
router.post('/store', controller.checkBeforeStoringReview);
router.get('/edit/:id', controller.editReview);
router.post('/update', controller.checkBeforeUpdatingReview);
This is the function to check auth before updating.
checkBeforeUpdatingReview: function(req, res) { // auth before updating review (can't use session or cookies)
console.log(req.body)
DB
.User
.findOne(
{
where : {
email: req.body.email,
},
}
)
.then (function (results) {
if (results[0] != '') {
if (bcrypt.compareSync(req.body.password, results.password)) {
return module.exports.updateReview(req, res, results)
} else { // same as catch
return res.render('reviews/edit/', { // i'm missing the ID (which i have in req.params.id) at the end of the route
id : req.params.id,
errors : "Incorrect username or password",
email : req.body.email,
});
}
}
})
.catch (function (error) {
console.log(error)
return res.render('reviews/edit/', { // i'm missing the ID (which i have in req.params.id) at the end of the route
id : req.params.id,
errors : "An unexpected error happened",
email : req.body.email,
});
})
},
If everything's ok, as seen above, it goes directly to this function
updateReview: function(req, res, results) { // update review
console.log(req.body)
DB
.Review
.update(req.body,
{
where : {
id: req.body.review_id,
}
}
)
.then(function (results) {
return res.redirect('/series/detail/' + req.body.series_id)
})
.catch (error => {
return res.send(error)
})
},
TL;DR: If auth fails, should go back to the review url and send the data that was sent so that the user does not lose it.
So that's it, if I could use sessions/cookies I think I would be able to go back to the last route, but I can't for this.
Thanks in advance!

How to change pathname in URL inside http get request

I'm doing a GET request of some user ID and I really need to get that user profile by ID
app.get('/userID) but I don't want to see the ID in my web URL but the user name, how can I do that? I'm also using Reactjs, I don't know if I have to change in backend or frontend in this case.
Thanks for helping!
my code - backend:
const router = express.Router()
router.get('/:userId', (req, res, next) => {
let userID = req.params.userId
.....
})
my code - frontend:
componentDidMount() {
let theURL = window.location.pathname.split('/')[1]
let userID = theURL.replace(theURL, '/hellotest')
getUserProfile(userID).then(
response => {
this.setState({
userName: response.data.userName,
....
})
},
error => {
this.setState({
....
})
}
)
}
I've tried with window.location.pathname.replace(theURL, '/hellotest') and doesn't work.
Thanks for your help
req.originalUrl retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes
app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new'
console.dir(req.originalUrl) // '/admin/new'
console.dir(req.baseUrl) // '/admin'
console.dir(req.path) // '/new'
next()
})
You have to res.redirect at the end of your dynamic(/:id) route
res.redirect( req.originalUrl.split("?").shift() );

GET Request route MEAN

I'm creating a MEAN APP and upon registration I want to check if an email already exists. However the GET request doesn't show anything. Also no error.
server.js
...
// Set user routes
const userRoutes = require('./user/user_controller');
app.use('/user', userRoutes);
...'
user_controller.js
router.get('/:email', (req, res) => {
console.log('Requesting user');
User.findOne({'email': req.params.email})
.exec(function(err, user) {
if(err) {
console.log('Error getting the post');
} else {
res.send(user);
}
});
});
The GET route never enters because I also don't see the console.log at the beginning of the route. I expect the route to work when I call localhost/user?email=email
I have a POST route whih works perfectly for localhost/user - just to compare
router.post('/', (req, res) => {
user = req.body;
// Validation
req.checkBody('firstName', "Enter a valid firstname").exists().isAlpha();
req.checkBody('lastName', 'Enter a valid lastname').exists().isAlpha();
req.checkBody('email', 'Enter a valid email').exists().isEmail();
req.checkBody('password', 'Enter a valid password').exists().isLength({min:8});
const errors = req.validationErrors();
if(errors) {
res.json({errors: errors});
} else {
User.create(user)
.then((user) => res.send(user));
}
});
You are calling your route the wrong way,
You can do one of these things.
1) Change your route path to /
As you said you were calling it localhost/user?email=email because this matches the route path / not /:email and you can access it like req.query.email.
2) Change the way you're calling it
If you want to use with /:email route path call it like localhost/user/someemail.

How to make subsequent requests using mwbot requesting Mediawiki

I got this error when I make subsequent request using mwbot on node.
response:
{ login:
{ result: 'Aborted',
reason: 'Cannot log in when using MediaWiki\\Session\\BotPasswordSessionProvider sessions' } } }
I am reading pages from mediawiki by providing a title. I thought that every request would need to login to read, but it seemed that I was wrong because this error seemed to complain that I already have logged in. But I don't know how the session can be read or how to find out that I already logged in or not.
the route:
router.get('/wikipage/:title', function(req, res, next) {
let title = req.params.title;
const MWBot = require('mwbot');
const wikiHost = "https://wiki.domain.com";
let bot = new MWBot();
let pageContent = "wiki page not created yet, please create";
bot.login({
apiUrl: wikiHost + "/api.php",
username: "xxx#apiuser",
password: "xxxxx"
}).then((response) => {
console.log("logged in");
return bot.read(title);
}).then((response) => {
for(let prop in response.query.pages) {
pageContent = response.query.pages[prop]['revisions'][0]['*'];
console.log("pageContent:", pageContent);
break;
}
res.json({
data: pageContent
});
}).catch((err) => {
// Could not login
console.log("error", err);
});
});
module.exports = router;
I presume you are running this in a browser, in which case the browser takes care of session cookie handling. You can check it the usual way via document.cookie.

Resources