Can't get data when 400 error. in Flutter - ajax

I'm trying to implement login with the Dio package in my app. When I send the correct email and password I get a 200 status code and user data. But when I send the email or password incorrect backend sends 400 error code and data like this {"message": "User Not Exist","data": [],"status": false} the problem is I'm unable to get the data when I have 400 error because in dio catchError method I can get just error and stacktrace.
Future login(String username, String password) async {
try {
String url = "$baseUrl/admin/user/login";
print(url);
var res = await dio.post(
url,
data: {"email": username, "password": password},
);
if (res.statusCode == 400) {
print(res.data); <----- This dont print anything.
return false;
} else {
print(res.data);
return true;
}
// await Future.delayed(Duration(seconds: 4));
} catch (e, s) {<----- here I have just error and stacktrace not the data
print("stacktrace $s");
print("error $e");
}
}

I solved this issue using on DioError catch instead of the catch method.
Future login(String username, String password) async {
try {
String url = "$baseUrl/admin/user/login";
print(url);
var res = await dio.post(
url,
data: {"email": username, "password": password},
);
if (res.statusCode == 400) {
print(res.data); <----- This dont print anything.
return false;
} else {
print(res.data);
return true;
}
// await Future.delayed(Duration(seconds: 4));
} on DioError catch (e) {
print(e.response.data);<-----------here I can get the data
return e.response.data;
}
}

Take try..catch out and use this form:
dio.post(...).then((response) {...}).catch(...)
Then you can use response as you wish.
You can read this article

Related

ERROR: Could not find message body reader

I have the following error code 415 when trying to upload an image to my database and following error message:
RESTEASY003200: Could not find message body reader for type: interface org.springframework.web.multipart.MultipartFile of content type: multipart/form-data;
I believe something about my controller is wrongly setup.
My controller:
#PreAuthorize("hasAnyRole('ROLE_MANAGER', 'ROLE_ADMIN')")
#Path("upload/image/{DDSEmployeeId}")
public Response saveImage(#RequestBody MultipartFile file, #PathParam("DDSEmployeeId") String DDSEmployeeId){
System.out.println(file.getOriginalFilename());
System.out.println(DDSEmployeeId);
return doReturn(personService.saveImage(file, DDSEmployeeId));
}
My Front-End Axios call:
async sendImage ({ test }, file) {
console.log('file', file.values().next());
if (file == null) {
logError('sendImage failed');
} else {
try {
const response = await defaultAxiosClient.post(`people/upload/image/${this.selectedPerson.ddsemployeeId}`, file);
console.log(response);
} catch (exception) {
logError('sendImage failed', exception);
}
}
}
What am I doing wrong?

How to covert Json result into string in Blazor WebAssembly?

I want to convert the result into a string and pass it to the navigation path, but I couldn't do it, please help me.
HttpGet Controller
[HttpGet]
[Route("UserId")]
public async Task<ActionResult<ApplicationUser>> GetUserId(string Username)
{
var user = await userManager.FindByNameAsync(Username);
if (user == null)
return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User not exist" });
var result = await userManager.GetUserIdAsync(user);
return new JsonResult(result);
}
Controller return result
"85e39a3e-8101-4166-9193-5e41bec1a7ce"
Function
private async Task Login()
{
var user = new userName { Username = Username };
var loginUser = new LoginDb { Username = Username, Password = Password };
if (Username == null || Password == null)
{
toastService.ShowWarning("Please enter Username and Password");
}
else
{
user = await Http.GetFromJsonAsync<userName>("Authentication/UserId?Username=" + Username);
if (user != null)
{
string Id = System.Text.Json.JsonSerializer.Serialize(user);
var result = await Http.PostAsJsonAsync("Authentication/login", loginUser);
if (result.IsSuccessStatusCode)
{
NavigationManager.NavigateTo("/profile/" + Id);
toastService.ShowSuccess("Login successful");
}
else
{
toastService.ShowError("Username or Password is wrong");
}
}
else
{
NavigationManager.NavigateTo("/login");
}
}
}
OK, I can see a few problems.
On the Server:
[HttpGet]
[Route("UserId")]
public async Task<ActionResult<ApplicationUser>> GetUserId(string Username) // A
{
var user = await userManager.FindByNameAsync(Username);
if (user == null) // B
return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User not exist" });
var result = await userManager.GetUserIdAsync(user);
return new JsonResult(result);
}
First, your return type here is Task<ActionResult<ApplicationUser>> . ApplicationUser is tied to the backend Identity library, you can't and shouldn't use it for a DTO.
And you don't, in the end you have return new JsonResult(result); which is OK when you change the return type to just Task<ActionResult>.
On the client:
//user = await Http.GetFromJsonAsync<userName>("Authentication/UserId?Username=" + Username);
var userId = await Http.GetFromJsonAsync<string>("Authentication/UserId?Username=" + Username);
The endpoint returns a simple string. Json does not know about 'UserName' or anything else.
//string Id = System.Text.Json.JsonSerializer.Serialize(user); -- use UserId
You are serializing the Id (again) here, making it almost certainly invalid for an URL. So just skip that.

I'm getting "Unauthenticated" message with a valid token in Laravel Passport using Flutter

I built a Web Service using Laravel Passport for authentication, when I register a user, it generates an access token successfully, but when I am trying to retrieve the user info, I get unauthenticated.
The interesting part is that making the social sign up with Postman, the access token generated works, but when I make the sign up with the app, the access token is not valid.
This is my request code on my mobile app:
Future<Map> socialSignIn(UserSocialAuth userSocialAuth) async {
final String _socialPath = '/social_auth';
Future<Map> socialSignInResponse;
try {
socialSignInResponse = postRequest(_socialPath, userSocialAuth.toJson());
} catch (error, stackTrace) {
print("Exception ocurred: $error stackTrace: $stackTrace");
socialSignInResponse = jsonDecode('{"exception": $error, "stackTrace": $stackTrace}');
}
return socialSignInResponse;
}
/// POST Request
Future<Map> postRequest(String serviceName, Map data) async {
Map responseData = {};
FormData formData = FormData.fromMap(data);
_dio.options.connectTimeout = connectTimeout;
_dio.options.receiveTimeout = receiveTimeout;
try {
Response response = await _dio.post(
_endpoint + '$serviceName',
data: formData,
options: Options(
headers: {
'Authorization': await getAccessToken(),
'Accept': 'application/json'
}
)
);
if (response.statusCode == 200) {
responseData = response.data;
}
} catch (e) {
// An error was received
responseData = {
'error': 'No se pudo conectar con el servidor de $_appName',
'exception': e.toString()
};
}
return responseData;
}
And this is the request for the user data using access token:
Future<Map> currentUser(String accessToken) async {
final String _currentUserPath = '/user';
Future<Map> userDataResponse;
try {
userDataResponse = getRequest(_currentUserPath);
} catch (error, stackTrace) {
print("Exception ocurred: $error stackTrace: $stackTrace");
userDataResponse = jsonDecode('{"exception": $error, "stackTrace": $stackTrace}');
}
return userDataResponse;
}
/// GET Request
Future<Map> getRequest(String serviceName) async {
Map responseData = {};
_dio.options.connectTimeout = connectTimeout;
_dio.options.receiveTimeout = receiveTimeout;
try {
Response response = await _dio.get(
_endpoint + '$serviceName',
options: Options(
headers: {
'Authorization': await getAccessToken(),
'Accept': 'application/json'
}
));
if (response.statusCode == 200) {
responseData = response.data;
}
} catch (e) {
// An error was received
responseData = {
'error': 'No se pudo conectar con el servidor de $_appName',
'exception': e.toString()
};
}
return responseData;
}
I do not know why works with postman and not with the app.
I save the access token with SharedPreferences like this:
/// ----------------------------------------------------------
/// Method that returns the token from Shared Preferences
/// ----------------------------------------------------------
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<String> getAccessToken() async {
final SharedPreferences prefs = await _prefs;
String _authorizationToken;
if (prefs.getString(_accessTokenKey) != null) {
_authorizationToken = 'Bearer ' + prefs.getString(_accessTokenKey);
}
return _authorizationToken;
}
/// ----------------------------------------------------------
/// Method that saves the token in Shared Preferences
/// ----------------------------------------------------------
Future<bool> setAccessToken(String token) async {
final SharedPreferences prefs = await _prefs;
return prefs.setString(_accessTokenKey, token);
}

React native: How to validate username and password while submitting

I have validate username and password,if username and password is wrong ,then i want through error like 'Invalid username/password'.if any one know,pls let me know.
async submit() {
//Validating username and password
const { username, password } = this.state;
if(username == ''){
this.setState({error:'Username is required'});
} else if(password == ''){
this.setState({error:'Password is required'});
} else {
this.setState({error: null})
let collection={};
collection.username=this.state.username;
collection.password=this.state.password;
// console.warn(collection);
var url = 'my url';
try {
let response = await fetch(url,
{
method: 'POST', // or 'PUT'
body: JSON.stringify(collection), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
});
let res = await response.text();
// console.warn(res);
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
console.log(accessToken);
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
// console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
//Handle error
console.log('Success:',response);
let error = res;
throw error;
}
} catch(error) {
console.log("error " + error);
}
}
}
response after giving invalid username/password:
0 {…}
field :password
message :Incorrect username or password.
I have written code like this based on status to validated username/password is correct/wrong.so here am posting code if it is useful for anyone in future.below code is,
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
console.log('Success:',response);
this.setState({error:'Invalid username/password'});
let error = res;
throw error;
}

Meteor: Session problems

Im getting this error
TypeError: Cannot read property 'set' of undefined
Code is:
Router.map(function() {
this.route('/payment_return/:invoice_no/:amount/', {
where: 'server',
onBeforeAction: function() {
console.log("result");
result = paypal_return(this.params.invoice_no,this.params.amount,this.params.query.token,this.params.query.PayerID);
console.log(result);
if (result)
{
var tokens = this.params.amount*10;
console.log(tokens);
var playerId = this._id;
Session.set('selectedUser', playerId);
var selectedUser = Session.get('selectedUser');
Meteor.call('updateTokens', selectedUser, tokens);
this.response.end("Payment captured successfully");
}
else
{
this.response.end("Error in processing payment");
}
}
});
});
In, methods.js
Meteor.methods({
'updateTokens': function(selectedUser, tokens){
check(selectedUser, String);
check(tokens, Number);
var currentUserId = Meteor.userId();
if(currentUserId){
Meteor.users.update(selectedUser,
{ $inc: { 'profile.tokens': tokens}});
}
}
})
Basically, trying to update user's token amount after successful payment, but unfortunately it's returning just that error.
Sessions are only available in client side... Not sure where you are trying to call Session, but if Session package is included and you are calling Sessions.set/get on client it should work.
This looks like API call to me, so I will suggest you to use meteorhacks:picker
Then you can add on your server side:
var paymentRoutes= Picker.filter(function(req, res) {
return req.method == "POST"; //OR GET WHATEVER YOU NEED
});
paymentRoutes.route('/payment_return/:invoice_no/:amount/',
function(params, req, res, next) {
//UPDATE TOKEN
});
var paymentRoutes= Picker.filter(function(req, res) {
return req.method == "GET" || "POST";
});
paymentRoutes.route('/payment_return/:invoice_no/:amount/', function(params, req, res, next) {
result = paypal_return(params.invoice_no,params.amount,params.query.token, this.userId);
if (result){
var tokens = this.params.amount*10;
var playerId = this.userId;
Meteor.users.update({_id:playerId},{ $inc: { 'profile.tokens': tokens}});
res.end("Payment captured successfully");
}else{
res.end("Error in processing payment");
}
});
I hope this will be helpful, Cheers

Resources