ANgular js show always email successfully sent although not sent - angularjs

I want to send mail to user i succeeded for that using spring boot and angular but i have a problem is that in my console always show me the message that my mail: succeesfuly sent: as mail is sent to user:
this is my angular js controller.js:
$scope.sentMail = function() { var data = new FormData();var mail= $scope.account.mail;
console.log('test 1 :', $scope.account.mail);
console.log("sent mail");
$http.post(_contextPath + '/sentEmail',mail).then(Failure)
.catch(Success);
function Success(success) {
// console.log(response.data);
console.log(' email is successfully sent:', $scope.account.mail);
}
function Failure(error) {
console.log('A problem occurred while sending an email.');
}
}
this is my controller.java:
#RequestMapping(value = "/sentEmail", method = RequestMethod.POST, headers = "Accept=application/json")
public ModelAndView processForgotPasswordForm(ModelAndView modelAndView, HttpServletRequest request, #RequestBody String mail) throws MessagingException
{
System.out.println("print");
User optional= usersService.findByEmail(mail);
if((optional== null))
{
modelAndView.addObject("errorMessage", "We didn't find an account for that e-mail address.");
}
else{
optional.setResetToken(UUID.randomUUID().toString());
usersService.save(optional);
String appUrl = request.getScheme() + "://" + request.getServerName();
SimpleMailMessage passwordResetEmail = new SimpleMailMessage();
passwordResetEmail.setFrom("test#test.com");
passwordResetEmail.setTo(optional.getUserEmail());
passwordResetEmail.setSubject("Password Reset Request");
passwordResetEmail.setText("Hello "+ optional.getUserFirstname()+" "+ optional.getUserLastname()+", \n \n You recently request to reset your password for rotana platform. Please click the link below to reset it : \n \n"+ appUrl +":8080/neorchaWEBPlatform"+ "/reset?token=" + optional.getResetToken()
+"\n \n if you did not request a password reset, please ignore email or reply to let us know.\n \n Thanks, \n \n Rotana Group \n \n P.S. We also love hearing from you and helping you with any issues you have. Please reply to this email if you want to ask a question.");
modelAndView.addObject("ResetMessage", "An e-mail has been sent to " + optional.getUserEmail());
emailService.sendEmail(passwordResetEmail);
}
modelAndView.setViewName("forgotPassword");
return modelAndView;
}
any help,thanks in advance.

.then will handle 'successful' responses. .catch will handle any errors in your success or error functions. You don't have an error function registered. I believe your code should be setup something like this:
$http.post(_contextPath + '/sentEmail',mail).then(Success, Failure)
.catch(UnexpectedError);
function Success(success) {
// console.log(response.data);
console.log(' email is successfully sent:', $scope.account.mail);
}
function Failure(error) {
console.log('A problem occurred while sending an email.');
}
function UnexpectedError(error) {
console.log('Something unexpected happened in Success() or Failure()');
}
The success and error callbacks look at the status being returned by your server. From the Angular documentation:
A response status code between 200 and 299 is considered a success
status and will result in the success callback being called. Any
response status code outside of that range is considered an error
status and will result in the error callback being called. Also,
status codes less than -1 are normalized to zero. -1 usually means the
request was aborted, e.g. using a config.timeout. Note that if the
response is a redirect, XMLHttpRequest will transparently follow it,
meaning that the outcome (success or error) will be determined by the
final response status code.
see: https://docs.angularjs.org/api/ng/service/$http

Related

Getting status 400 as an error instead of json response

I have a front-end connected to back-end, using http requests.
I'm experiencing this thing where if I return res.status(200) I get a response which I can send with that response a message. But when I'm sending res.status(400). I'm getting an red error on console rather than a parsable response.
app.post('/new', (req, res) => {
const { fullname, phone, country, img } = req.body
return res.status(200).json({
title: 'Ok, we got you!'
})
})
// If I'm changing that status to 400 I get that red error on console and I cannot parse from it anything (anything atleast that I want)
Yes, and that's the correct behaviour with HTTP requests. HTTP 400 Bad Request indicates an error rather then a successful response from your web server. So you need to catch the error thrown by the server with either a .catch() clause or a try/catch block in order to access the data returned on your client side. You're server code is absolutely fine. Just add the code below to your client side application.
Using .catch approach
axios.get('/foo')
.catch(function(error) {
console.log(error.response.data);
console.log(error.response.data.title); // your title
console.log(error.response.status);
console.log(error.response.headers);
});
Using try/catch approach
try {
const resp = await axios.get('/foo');
} catch (error) {
console.log(error.response.data);
console.log(error.response.data.title); // your title
console.log(error.response.status);
console.log(error.response.headers);
}
For more information visit this link

REDUX SAGA - API Retry Isomorphic Fetch

I am trying to add RETRY Logic in the context of - I make an API call -> response is 401 -> I invoke APi to request for a NEW Token in the background. The poin there si MY API Calls shouldnt fail. Following is my API File (This is common - Every API in my application invokes this File to make an FETCH)
NOTE : I have seen articles using the fetch().then() approach, but we are using YIELD.
Specific API File -
// apiRequest = part of api.js file i am specifying below
const response = yield retry(3,1000,apiRequest,options); // My apiRequest while trying for getting new access tokens send me a NULL, do we want that ?
if (undefined !== response && null !== response) {
const formattedResponse = yield apply(response, response.json);
if (response.status === 200) {
yield call(handleAddCampaignResponseSuccess, formattedResponse);
} else {
yield call(handleAddCampaignResponseFailure, formattedResponse);
}
} else{
// Show some Message on UI or redirect to logout
}
// api.js
function* apiRequest(options) {
const { method, body, url } = options;
const accessToken = yield select(selectors.AccessToken);
const idToken = yield select(selectors.IdToken);
try {
var response = yield call(fetch, url, {
method: method,
body: body,
headers: {
"Content-Type": ContentTypes.JSON,
Authorization:
accessToken != "" ? `Bearer ${accessToken} ${idToken}` : "",
},
});
if (null !== response) {
if (response.status === HTTP_CODES.HTTP_UNAUTHORIZED) {
// Unauthorized requests - redirect to LOGOUT
// Request for Refresh Token !
yield put(refreshTokenOnExpiry());
return null; // Is this necessary
} else if (response.status === HTTP_CODES.HTTP_NOT_FOUND) {
return null;
} else if (response.status === HTTP_CODES.HTTP_SERVER_ERROR) {
// Logout cos of serrver error
yield put(handleLogout());
return null;
} else {
console.log("From Else part");
// - Called on intent to ensure we have RESET redirections and that it does not cause issues of redirection.
yield put(resetRedirections());
return response;
}
} else {
// Handle Logout
yield put(stopTransition());
yield put(handleLogout());
}
} catch (error) {
// Cors Error in case of DEV URL
// See if SAGA is Still listening to the Action Dispatches
console.log("From CATCH BLOCK");
yield put(stopTransition());
yield put(handleLogout());
return null;
}
}
My concern is the documentation says that - if API request fails then it will retry, I do not get the meaning of it. Does it mean if the API returns NULL, or anything other than Http 200 ? Cos I want the API to retry in case of 401
API.JS is the file invoked by ALL API's across my website. Also, how can I ensure that refreshTokenOnExpiry gets called ONLY once (meaning at a time there will be multiple API calls and each one when got a 401 will eventually invoke refreshTokenOnExpiry this API)
I am new to generator functions, so I am sure I must have goofed up somewhere.
Also if anyone who can help me build this code correctly, would be great help. Thanks !
Adding Image for reference - I want the FAILED API's to be retried which aint happening :
My concern is the documentation says that - if API request fails then it will retry, I do not get the meaning of it. Does it mean if the API returns NULL, or anything other than Http 200 ? Cos I want the API to retry in case of 401
Scroll down to the section "Retrying XHR calls" in the redux-saga recipes to get an idea of what the retry effect is doing behind the scenes.
The retry effect can be used on any function, no just an API call, so it's not looking at the response code. It defines "failure" as code that throws an error rather than completing execution. So what you need to do is throw an error in you apiRequest.
No guarantees, but try this:
if (response.status === HTTP_CODES.HTTP_UNAUTHORIZED) {
// Unauthorized requests - redirect to LOGOUT
// Request for Refresh Token !
yield put(refreshTokenOnExpiry());
throw new Error("invalid token");
}
You need to figure out how to make sure than the new token gets set before retrying. You might want to build your own chain of actions rather than relying on retry. For example, you can put an action with type "RETRY_WITH_NEW_TOKEN" that has a payload containing the original options and the token that it was tried with. That way you can compare it against the token in state to see if you have a new one.

$http request does not execute after a day or 2 on RHC

We have a Node JS - Express application running on a Openshift RHC v2 and an api is being called to a third party SMS gateway server whenever a user requests for an OTP. For this we have added a simple $http call which will trigger an SMS to the mentioned number with the message.
The request looks something like this :
$http.get("http://example.com/?user=userid:password&number=9876543210&message='Hi your OTP is 18276'")
.success(function(error, response){
if (!error && response.statusCode == 200) {
console.log('STATUS: ' + response.statusCode)
console.log('HEADERS: ' + JSON.stringify(response.headers));
} else {
console.log('STATUS : '+ error.statusCode);
console.log(error);
}
});
This works as soon as the RHC Server starts running. After a few days or sometimes a few hours we observe that this API is never called. We have added console logs before and after the requests and still the API is never called. It is very very surprising and shocking how can it not execute this request (which is working for a few days and then goes down completely).
What could be the issue here? Will re-share what we have :
console.log("Generated OTP : " + otp); // ... Where OTP is what we have generated... Console 1
var number = 9876543210;
var message = 'Hi your OTP is : '+otp;
console.log('Number : ' + number + ', Message : ' + message); // ... Console 2
$http.get("http://example.com/?user=userid:password&number="+number+"&message="+message)
.success(function(error, response){
if (!error && response.statusCode == 200) {
console.log('STATUS: ' + response.statusCode) ... Console 3
console.log('HEADERS: ' + JSON.stringify(response.headers)); // ... Console 4
} else {
console.log('STATUS : '+ error.statusCode); // ... Console 5
console.log(error); // ... Console 6
}
});
console.log("callback - Post - /sellers/phone/:number/:email"); // ...Console 7
res.json({"otp":otp});
When this is down, Consoles 1, 2 and 7 can be seen but not 3, 4 or 5 and 6.
Is there any way we can debug either on the Openshift or on the Node application?
If I do a server restart using rhc app-restart <app> the other consoles will be seen and we receive the SMS / Messages.
Please help. Any additional information needed, please let us know.
Thank you.
EDIT : I have also tried using request as below :
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
} else {
console.log('STATUS : ' + error.statusCode);
console.log(error);
}
});
Since AngularJS v1.6 the .success() and .error() methods on promises are removed.
Instead use the .then() method. All the data for the success, errors and headers are moved to the .then(response) response data.
So:
response.config, // Contains an object of configurations, like `Method`, `params`, `URL`
response.data, // Contains the data the request returned
response.status, // Contains the status code, Eg 200 which is success
response.statusText, // Text of the status, Eg. Ok on success or Error on error
So check whether the $http method succeeded like so:
$http.get("http://example.com/?user=userid:password&number="+number+"&message="+message)
// Use .then instead of .success
.then(function (response) {
if(response.status === 200) {
// Successfull
} else {
// Error occurred
}
});
Just incase you wonder why they are removed. Check out this topic:
Why are angular $http success/error methods deprecated? Removed from v1.6?

Why restangular is giving an error although the request is successfull

I am using Restangular to consume a REST API and it always gives me this error even though I can see the XHR request being made successfully on the developer console.
Error
{
"data":null,
"status":-1,
"config":{
"method":"GET",
"transformRequest":[null],
"transformResponse":[null],
"jsonpCallbackParam":"callback",
"headers":{"Accept":"application/json, text/plain, */*"},
"url":"http://localhost:8080/profile/v1/support/tickets"},
"statusText":""
}
Restangular API call
angular.module('adf-widget-tickets-module-service',['restangular'])
.service('ticketCRUDService', function ($rootScope, Restangular, $http) {
Restangular.setBaseUrl('http://localhost:8080/profile/v1/support');
this.readTickets = function () {
Restangular.all('tickets').getList().then(function (response) {
var test = response.json;
console.log(test);
return test;
},function (err) {
console.error(JSON.stringify(err));
},function () {
console.log("loading......");
})
};
}
Could you please tell me what am I doing wrong here?
Update
Here is the code for my REST endpoint
#GET
#Path("tickets")
#Produces("application/json")
public Response getAllTickets(){
ArrayList<Ticket> allTickets = new ArrayList<>();
try {
allTickets = elasticAPI.getAllTickets();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return Response.ok(gson.toJson(allTickets), MediaType.APPLICATION_JSON_TYPE).build();
}
why your endpoint is returning a -1 status code?
Angular resolves only between: 200 and 299
/*
* A response status code between 200 and 299 is considered a success status and will result in
* the success callback being called. Any response status code outside of that range is
* considered an error status and will result in the error callback being called.
* Also, status codes less than -1 are normalized to zero. -1 usually means the request was
* aborted, e.g. using a `config.timeout`.
* Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
* that the outcome (success or error) will be determined by the final response status code.
*/
https://github.com/angular/angular.js/blob/master/src/ng/http.js#L457
As I guessed the problem was not on my client side code. It was because of that the request being rejected from the server due to CORS. Setting proper response headers for CORS support fixed the problem.

Message failure in channel api

I am running a gae web app on localhost.
I have successfully generated a token from goog.channel and send it to client. Where client is able to accept the token and tries to open connection. The problem is that, I am sending a message from my servlet class and nothing is happening in client side.
Below are my codes:
Server Side:
//for generating token
ChannelService channelService=ChannelServiceFactory.getChannelService();
token = channelService.createChannel(userid);
//for sending message
ChannelService channelService=ChannelServiceFactory.getChannelService();
channelService.sendMessage(new ChannelMessage(userid, message));
//in appengine-web.xml
<inbound-services>
<service>channel_presence</service>
</inbound-services>
Javascript:
function getToken(){
var xmlhttpreq=new XMLHttpRequest();
xmlhttpreq.open('GET',host+'/channelapi_token?q='+user,false);
xmlhttpreq.send();
xmlhttpreq.onreadystatechange=alert(xmlhttpreq.responseText);
token=xmlhttpreq.responseText;
setChannel();
}
function setChannel(){
alert(token);//iam receiving right token here
channel=new goog.appengine.Channel(token);
socket=channel.open();
socket.open=alert('socket opened');//this message alerts
socket.onmessage=alert('socket onmessage');//this message alerts
socket.onerror=alert('socket onerror');//this message alerts
socket.onclose=alert('socket onclose');//this message alerts
}
There are no exceptions while sending message from channelservice.
Also the client side is repeatly making a get request to my server:
http://localhost:8888/_ah/channel/dev?command=poll&channel=channel-h1yphg-vivems#gmail.com&client=connection-3
What's the wrong happening here?
Thanks in advance.
You're calling alert(...) and assigning its return value to your message handlers. You should assign a function to these handlers instead:
socket.onopen = function() {
alert('socket opened');
};
// etc
// Note that message takes a parameter:
socket.onmessage = function(evt) {
alert('got message: ' + evt.data);
};
Note you can also do this like:
function onMessage(evt) {
// do something
}
socket.onmessage = onMessage;
Note that you're not assigning onMessage(), which will call onMessage and assign its return value.

Resources