This is my API route in nodejs:
router.get('/reset/:token', function(req, res) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
res.json('Password reset token is invalid or has expired.');
//return res.j('/forgot');
}
res.json('Goed');
});
});
Now when I want to test this in Postman, I use this incorrect way:
Postman Screenshot
I normally don't work with params, how can I test this?
You can use URL segment parameters like this:
URL: http://localhost:3000/reset/:id
And a URL parameter:
id = 65bb...
2 issues.
1. In screen shot the method is POST but your code waiting for GET request.
2. use this url: http://localhost:3000/reset/6b.... do not use token=
Just pass the token as the last part of the path, like so:
localhost:3000/reset/65bb...
Optionally, if you want to pass the token as a query parameter (like you do in your Postman screenshot), define the route like this:
router.get('/reset', function(req, res) {
// In here, use req.query.token instead of req.params.token
}
Related
I try to make my api.
it should look like this:
http://test.com/api/genpw/KEY=key/TYPE=BASE64/HEX
the request should come back like this:
{
APIKEY: "KEY",
TYPE: "BASE64 / HEX"
PASSWORD: "GENERATED PW"
}
How do I do this and how can I do this?
I don't think these parameters should be part of the URL. Following the REST API standard, they should be query parameters and the URL must be: http://test.com/api/genpw?key=some-value&type=base64
Example how to get query parameters in express:
app.get('/api/content', async (req, res) => {
const {key, type, password} = req.query;
res.send('success');
}
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.
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!
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
I have a functionality of verifying a user by clicking a link from Email. I have field in Mongo User Collection called Active. This is a boolean. when User register, Active will be false. When they click the link active will change to true. My issue is that link is working well in postman but not working in browser URL.
My Code
verify = (req, res) => {
User.update({ email: req.query.mail }, { $set: { active: true } }, (err, user) => {
if (err) {
res.send(err);
} else {
res.send(user);
}
});
}
My API: POST api/user/verifySignin
My Link: http://localhost:3000/api/user/verifySignin?mail=abc#xyz.com
I used this link in browser URL its not working, But I used in POSTMAN its working. Help me, where I am going wrong
You can't make post requests from an URL directly in your browser, you need to either use an XMLHTTP request library like fetch or use a <form action="http://localhost:3000/api/user/verifySignin?mail=abc#xyz.com" method="post">
try $http to pass the url
$http.post(http://localhost:3000/api/user/verifySignin)