Perform POST from Browser URL - node.js

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)

Related

Getting an empty object in Axios Get Request

I am trying to set up a get route using axios. I am using React. I am trying to get the state of user.
user.user logs:
{_id: '62c5bdda933b818e12bef350', username: 'JordanF', Profiles: Array(9), createdAt: '2022-07-06T16:52:42.396Z', updatedAt: '2022-07-09T19:24:10.523Z', …}
I am trying to display username on my page. But at the moment I can't even log the username to my backend, so won't be able to search my db.
Profile.jsx
function getUser(data) {
console.log(data)
axios({
url: `http://localhost:3000/profiles`,
method: "GET",
data: data
})
.then((response) => console.log(response))
}
useEffect(() => {
setProfileList(profiles)
getUser(user.user)
},[]);
Data logs the data in the front end that I would like to get in the backend
BackEnd Controller
I have tried a lot of different syntax for this, this is my most recent. In the backend temrinal my console.log hits, and req.body returns an empty object.
async function getUser(req,res){
console.log('getUser hit')
function log(){
console.log(req.body)
return req.body
}
await log()
}
Yup! I was being silly. GET requests are only really concerned with params. I changed my route, so that the User's ID was in the URL path, and used req.params.id and everything worked out!

problem on creating new document in mongoose

i want to add a new document with mongoose
but it just creates only the _id without all the details I entered
in the postman i entered:
{
"name":"jhon",
"email":"jhon11#gmail",
"password":"1234"
}
but got this in the res:
{
"_id": "6072e8d3f0f69037cc05b8cb",
"__v": 0
}
my code:
const addUser = async (req, res) => {
try {
let user = new User(req.body)
await user.save()
res.send(user)
}
catch (error) {
res.status(400).send(`error ${error}`)
}
}
and the schema is:
const userSchema=mongoose.Schema({
name:{
Type:String
},
email:{
Type:String
},
password:{
Type:String,
}
})
thanks for any advice.
Postman isn't very straight forward in explaining how it sends out post requests. I'm saying this because I also had some run-downs with it. It is most likely sending out an empty body in the request. Open up postman again, and go to the post request you created. We already know your request reached the backend server, so it means the url is fine, and that its type is in fact a post request. So now, click on the Body tab.
I'm gonna go ahead and guess you chose the raw option amongst the million available options there, correct?
In the textarea zone, insert your raw json again, as you did before:
{
"name":"jhon",
"email":"jhon11#gmail",
"password":"1234"
}
But wait! before sending that out, look to the right. There's a combo-box there. A dropdown. A select menu (whatever you wanna call it).
By default, postman chooses TEXT as the default option. Change it to JSON!
NOW IT'S GONNA WORK!
Also, maybe before sending that out for test spin, i'd recommend putting a console.log in bewtween your lines and see what prints out, like so:
const addUser = async (req, res) => {
try {
let user = new User(req.body)
console.log('req.body is:', req.body)
await user.save()
res.send(user)
}
catch (error) {
res.status(400).send(`error ${error}`)
}
If your req.body is still being presented as empty, then my next question to you would be: Are you using bodyParser on your server? Because could also be the case. Body parser, as its name suggests, is meant for dealing with req.body, so it could actually be readable. try adding a body parser to your express server.
Good luck!
I hope that helps.

How do I check a specific field in a MongoDB Document using Express & Passportjs

I have a NodeJS Web application running and it has express, mongoose, passportjs among other unrelated modules to this question.
There are two types of users and each has their own collection in my database.
User
Admin
When a User successfully signs in through the login page, they get redirected to "/memberdashboard".
Similarly, when an Admin successfully signs in through the login page, they get redirected to "/admindashboard".
Both collections have a "username" and "password" field.
However in my Admin collection, there is an extra field "isAdmin" which is of type Boolean.
I want to redirect someone who logs in to my website based on whether or not they are admin.
So for example, if userA has {"isAdmin" : true}, they will be redirected to /admindashboard else they will be redirected to /memberdashboard.
Some code that might help explain what I'm trying to achieve.
app.get("/memberdashboard", function(req, res) {
if(req.isAuthenticated()) {
res.render("memberdashboard");
} else {
res.redirect("/member");
}
});
app.get("/admindashboard", function(req, res) {
if(req.isAuthenticated()) {
res.render("admindashboard");
} else {
res.redirect("/admin");
}
});
My goal is making use of that
if(req.isAuthenticated() && //User is Admin) {
//redirect to appropriate page
}
Hope this was clear :)
Afaik passport populates req.user once the user is authenticated. So you could expand your check for /membershipdashboard to:
if (req.isAuthenticated()) {
if (req.user.isAdmin) {
return res.redirect("/admin");
}
res.render("memberdashboard");
} else {
res.redirect("/member");
}
You can do this vice-versa for the /admindashboard-route.

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!

Testing a post API call that has a param with Postman

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
}

Resources