I have a nodejs/express api that works fine except for one endpoint.
This endpoint is the one that resets the passwords for users.
It looks like this:
adminUserRoutes.post('/forgotPassword', (req, res) => {
console.log('it connected')
if (req.body.email === '') {
res.status(400).send('email required');
}
User.findOne({email: req.body.email}, (err, user) => {
console.log('and here')
if(user){
const token = crypto.randomBytes(64).toString('hex');
console.log('use',user)
user.resetPasswordToken = token
user.resetPasswordExpires = Date.now() + 360000
user.name = user.name
user.email = user.email
user.password = user.password
user.admin = user.admin
// console.log(user)
user.save()
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: `username`,
pass: `password`,
},
});
const mailOptions = {
from: 'devinjjordan@gmail.com',
to: `${user.email}`,
subject: 'Link To Reset Password',
text:
'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n'
+ 'Please click on the following link, or paste this into your browser to complete the process within one hour of receiving it:\n\n'
+ `http://localhost:3000/#/newpassword/${token}\n\n`
+ 'If you did not request this, please ignore this email and your password will remain unchanged.\n',
};
console.log('sending mail');
transporter.sendMail(mailOptions, (err, response) => {
if (err) {
console.error('there was an error: ', err);
// res.status(200).json('there was an error: ', err);
} else {
console.log('here is the res: ', response);
res.status(200).json('recovery email sent');
}
});
} else {
console.error('email not in database');
res.status(403).send('email not in db');
}
})
});
When I make a request to that endpoint, I receive this error:
Access to XMLHttpRequest at 'https://vpt4tz7x26.execute-api.us-east-1.amazonaws.com/dev/api/users/forgotPassword' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What makes is odd is that when I run the api with sls offline start, the code works as expected, however, when I deploy to aws, I receive the above error.
This is my serverless.yml:
service: news-api # NOTE: update this with your service name
provider:
name: aws
runtime: nodejs10.x
functions:
app:
handler: app.handler
# The `events` block defines how to trigger the http events
events:
- http: ANY /
- http: 'ANY {proxy+}'
plugins:
- serverless-offline