React-native-uploader Android Errors - java

I'm currently trying to debug a react-native package (react-native-uploader) I'm using to try and upload a bundle of files (photos). Despite working on ios, the current implementation is returning the following error for android:
Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=${config.apiBase}/load/${this.props.id}/uploadconfirmation}
The error is originating from this line in the package:
Response response = client.newCall(request).execute();
Where the client is:
private final OkHttpClient client = new OkHttpClient()
Where request is:
Request{method=POST, url=${config.apiBase}/load/${this.props.id}/uploadconfirmation, tag=null}
I've successfully made posts to the endpoint using formdata:
let tData = new FormData();
const that = this;
tData.append("confirmation_doc", {
uri: files[0].filepath,
type: "image/jpeg",
name: "confirmation_doc.jpg",
});
axios.post(
`${config.apiBase}/load/${this.props.id}/uploadconfirmation`,
tData
)
.then(response => {
Alert.alert(
"Success",
"Uploaded Successfully!",
[{ text: "OK", onPress: () => that.props.close() }],
{ cancelable: false }
);
});
I've tried looking through the source code to determine where things are falling apart and it seems like everything is posting as it should (headers look good, method looks good, endpoint looks good). I'm not all too familiar with Java so any input would be appreciated.

HTTP 405 Method Not Allowed ... is a client-side error.
The method received in the request-line is known by the origin server but not supported by the target resource.
if the JavaScript works, but the Java won't... you might be looking for the MultipartBuilder
... in combination with MediaType.FORM.

In order to solve this issue, I had to abandon the react-native-uploader package I had been using. Below is how I managed to resolve the issue:
let tData = new FormData();
this.state.selectedImages.forEach((item, i) => {
tData.append("doc[]", {
uri: item.uri,
type: "image/jpeg",
name: item.filename || `filename${i}.jpg`,
});
});
fetch(`${config.apiBase}/load/${this.props.id}/uploadconfirmation`, {
method: "post",
headers: {
Accept: "application/x-www-form-urlencoded",
Authorization: `Token ${this.props.token}`,
},
body: tData,
})
.then(res => res.json())
.then(res => {
Alert.alert(
"Success",
"Uploaded Successfully!",
[{ text: "OK", onPress: () => that.props.close() }],
{ cancelable: false }
);
})
.catch(err => {
console.error("error uploading images: ", err);
});

Related

why is React Native HTTP POST not working?

export const login = () => {
return async (dispatch) => {
try {
const response = await fetch(
`https://simplyrem.com/srwl/haib/index.php`,
{
method: 'POST',
headers: {
accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
auth: 'XCXCXCXCX',
usernamex: 'XXXXX',
passwordx: 'XXXXXXXX',
}),
}
)
if (!response.ok) {
const errorResData = await response.json()
console.log(errorResData)
throw new Error('Something went wrong!')
}
const responseData = await response.json()
const userInfo = responseData
console.log(userInfo)
dispatch({
type: LOGIN,
userInfo: userInfo,
})
} catch (err) {
throw err
}
}
}
Hello all,
I have tested this API using insomnia while inputting my credentials and I got a JSON response back, so I know that the API works and my credentials are correct. I am new to React Native and I don't know if I'm adding the parameters correctly by using body: JSON.stringify... Obviously, I've replaced the information with "X"s. In swift, I was able to also get a response back, but when I'm trying to recreate the API call in react-native I get error
> [Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected EOF]
> * [native code]:null in parse
> - node_modules/react-native/node_modules/promise/setimmediate/core.js:37:13 in tryCallOne
> - node_modules/react-native/node_modules/promise/setimmediate/core.js:123:24 in setImmediate$argument_0
> - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:130:14 in _callTimer
> - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:181:14 in _callImmediatesPass
> - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:441:30 in callImmediates
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:387:6 in __callImmediates
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:135:6 in __guard$argument_0
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:364:10 in __guard
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:134:4 in flushedQueue
> * [native code]:null in flushedQueue
> * [native code]:null in invokeCallbackAndReturnFlushedQueue >
JSON Parse error: Unexpected EOF it's usually
an error when you are trying to convert the non-covertable response to json (like Html response) into json
for safety I usually convert it first to string using .then(res => res.text()) then console.log() or alert() it to prove the response is Convertable to json or not without showing the react-native's red-box message,
if the response is valid json you can convert it by yourself with JSON.parse(responseText)
example like
fetch( "https://simplyrem.com/srwl/haib/index.php", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
Email: 'XXXXX',
password: "xxxxx",
}),
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.IsSuccess) {
console.log(responseJson);
alert(responseJson)
} else {
console.log(responseJson.ErrorMessage);
alert(responseJson.ErrorMessage)
}
})
.catch((error) => {
alert(error);
});

Request works in postman not IONIC

I'm developing an ionic app with a back-end with Java spring Boot with Spring security on it. When I tried to get a token with postman everything went well but in ionic, I got a 401 HTTP code. I have no cors problem, I have disabled it in my browser.
Here is the code from Ionic:
login() {
return new Promise((resolve, reject) => {
var credentials = "grant_type=password" + "&username=admin" + "&password=admin";
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
headers.append('Authorization', 'Basic c2NhbnRhYm91ZmZlOlhZN2ttem9OemwxMDA=');
console.log(headers.toString);
this.http.post('http://localhost:8443/oauth/token', credentials, {
headers: headers
})
.subscribe(res => {
console.log(res);
let data = JSON.parse("" + res.toString); // res.json();
this.token = data.token;
this.storage.set('token', data.token);
resolve(data);
resolve(JSON.parse("" + res.toString) /* res.json() */ );
}, (err) => {
reject(err);
});
});
}
Thx for yr help I'm stuck on it for more than 3 weeks

Server Data is not Coming: Angular2

I have created a simple app using REST in java which return string value successfully with REST client. Now I want to get string value using Http rest client in Angular2. I have created service for getting data from rest client in angular2 which saying successfully access rest but when I am printing data like {{serverData}} it's print nothing.
service.ts
#Injectable()
export class HttpSiftgridService {
private url:string = "http://localhost:8080/app-rest/rest /get/getData";
constructor(private _http: Http) {}
getSiftgridData() {
alert(this._http.get(this.url).map(res => res.json));
alert("hh");
return this._http.get(this.url).map(res => res.json);
}
private handleError(error : Response) {
console.error(error);
return Observable.throw(error.json().error || ' error');
}
}
app.component.ts
export class AppComponent implements OnInit{
serverData: string;
constructor(private _httpService:HttpSiftgridService) {}
ngOnInit() {
this._httpService.getSiftgridData()
.subscribe(
data => this.serverData = JSON.stringify(data),
error => console.log("Error in getting Data"),
() => console.log("Successfully")
);
}
}
my rest app running on tomcat.
Change:
return this._http.get(this.url).map(res => res.json);
To:
return this._http.get(this.url).map(res => res.json());
I know it's not a real answer but that wouldn't work as comment:
If you change it to
ngOnInit() {
this._httpService.getSiftgridData()
.subscribe(
data => {
this.serverData = JSON.stringify(data);
console.log(data);
},
error => console.log("Error in getting Data"),
() => console.log("Successfully")
);
}
is the data printed?
Is Successfully printed?

custom error message in ajax from spring controller [duplicate]

Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?
For example, if I want to throw an exception on the server side via Struts by throw new ApplicationException("User name already exists");, I want to catch this message ('user name already exists') in the jQuery AJAX error message.
jQuery("#save").click(function () {
if (jQuery('#form').jVal()) {
jQuery.ajax({
type: "POST",
url: "saveuser.do",
dataType: "html",
data: "userId=" + encodeURIComponent(trim(document.forms[0].userId.value)),
success: function (response) {
jQuery("#usergrid").trigger("reloadGrid");
clear();
alert("Details saved successfully!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
On the second alert in the error callback, where I alert thrownError, I am getting undefined and the xhr.status code is 500.
I am not sure where I am going wrong. What can I do to fix this problem?
Make sure you're setting Response.StatusCode to something other than 200. Write your exception's message using Response.Write, then use...
xhr.responseText
..in your javascript.
Controller:
public class ClientErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
response.Write(filterContext.Exception.Message);
response.ContentType = MediaTypeNames.Text.Plain;
filterContext.ExceptionHandled = true;
}
}
[ClientErrorHandler]
public class SomeController : Controller
{
[HttpPost]
public ActionResult SomeAction()
{
throw new Exception("Error message");
}
}
View script:
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
ServerSide:
doPost(HttpServletRequest request, HttpServletResponse response){
try{ //logic
}catch(ApplicationException exception){
response.setStatus(400);
response.getWriter().write(exception.getMessage());
//just added semicolon to end of line
}
}
ClientSide:
jQuery.ajax({// just showing error property
error: function(jqXHR,error, errorThrown) {
if(jqXHR.status&&jqXHR.status==400){
alert(jqXHR.responseText);
}else{
alert("Something went wrong");
}
}
});
Generic Ajax Error Handling
If I need to do some generic error handling for all the ajax requests. I will set the ajaxError handler and display the error on a div named errorcontainer on the top of html content.
$("div#errorcontainer")
.ajaxError(
function(e, x, settings, exception) {
var message;
var statusErrorMap = {
'400' : "Server understood the request, but request content was invalid.",
'401' : "Unauthorized access.",
'403' : "Forbidden resource can't be accessed.",
'500' : "Internal server error.",
'503' : "Service unavailable."
};
if (x.status) {
message =statusErrorMap[x.status];
if(!message){
message="Unknown Error \n.";
}
}else if(exception=='parsererror'){
message="Error.\nParsing JSON Request failed.";
}else if(exception=='timeout'){
message="Request Time out.";
}else if(exception=='abort'){
message="Request was aborted by the server";
}else {
message="Unknown Error \n.";
}
$(this).css("display","inline");
$(this).html(message);
});
You need to convert the responseText to JSON. Using JQuery:
jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);
If making a call to asp.net, this will return the error message title:
I didn't write all of formatErrorMessage myself but i find it very useful.
function formatErrorMessage(jqXHR, exception) {
if (jqXHR.status === 0) {
return ('Not connected.\nPlease verify your network connection.');
} else if (jqXHR.status == 404) {
return ('The requested page not found. [404]');
} else if (jqXHR.status == 500) {
return ('Internal Server Error [500].');
} else if (exception === 'parsererror') {
return ('Requested JSON parse failed.');
} else if (exception === 'timeout') {
return ('Time out error.');
} else if (exception === 'abort') {
return ('Ajax request aborted.');
} else {
return ('Uncaught Error.\n' + jqXHR.responseText);
}
}
var jqxhr = $.post(addresshere, function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function(xhr, err) {
var responseTitle= $(xhr.responseText).filter('title').get(0);
alert($(responseTitle).text() + "\n" + formatErrorMessage(xhr, err) );
})
If someone is here as in 2016 for the answer, use .fail() for error handling as .error() is deprecated as of jQuery 3.0
$.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
//handle error here
})
I hope it helps
This is what I did and it works so far in a MVC 5 application.
Controller's return type is ContentResult.
public ContentResult DoSomething()
{
if(somethingIsTrue)
{
Response.StatusCode = 500 //Anything other than 2XX HTTP status codes should work
Response.Write("My Message");
return new ContentResult();
}
//Do something in here//
string json = "whatever json goes here";
return new ContentResult{Content = json, ContentType = "application/json"};
}
And on client side this is what ajax function looks like
$.ajax({
type: "POST",
url: URL,
data: DATA,
dataType: "json",
success: function (json) {
//Do something with the returned json object.
},
error: function (xhr, status, errorThrown) {
//Here the status code can be retrieved like;
xhr.status;
//The message added to Response object in Controller can be retrieved as following.
xhr.responseText;
}
});
A general/reusable solution
This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:
Custom exception ModelStateException that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)
Custom controller action error filter HandleModelStateExceptionAttribute that catches custom exception and returns HTTP error status with model state error in the body
This provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success and error handlers.
Client side code
$.ajax({
type: "POST",
url: "some/url",
success: function(data, status, xhr) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
Server side code
[HandleModelStateException]
public ActionResult Create(User user)
{
if (!this.ModelState.IsValid)
{
throw new ModelStateException(this.ModelState);
}
// create new user because validation was successful
}
The whole problem is detailed in this blog post where you can find all the code to run this in your application.
error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
in code error ajax request for catch error connect between client to server
if you want show error message of your application send in success scope
such as
success: function(data){
// data is object send form server
// property of data
// status type boolean
// msg type string
// result type string
if(data.status){ // true not error
$('#api_text').val(data.result);
}
else
{
$('#error_text').val(data.msg);
}
}
I found this to be nice because I could parse out the message I was sending from the server and display a friendly message to the user without the stacktrace...
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
This function basically generates unique random API key's and in case if it doesn't then pop-up dialog box with error message appears
In View Page:
<div class="form-group required">
<label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
<div class="col-sm-6">
<input type="text" class="apivalue" id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />
<button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
</div>
</div>
<script>
$(document).ready(function(){
$('.changeKey1').click(function(){
debugger;
$.ajax({
url :"index.php?route=account/apiaccess/regenerate",
type :'POST',
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function(data){
var result = data.sync_id.toUpperCase();
if(result){
$('#api_text').val(result);
}
debugger;
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
});
</script>
From Controller:
public function regenerate(){
$json = array();
$api_key = substr(md5(rand(0,100).microtime()), 0, 12);
$json['sync_id'] = $api_key;
$json['message'] = 'Successfully API Generated';
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails.
The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
This is probably caused by the JSON field names not having quotation marks.
Change the JSON structure from:
{welcome:"Welcome"}
to:
{"welcome":"Welcome"}
You have a JSON object of the exception thrown, in the xhr object. Just use
alert(xhr.responseJSON.Message);
The JSON object expose two other properties: 'ExceptionType' and 'StackTrace'
I believe the Ajax response handler uses the HTTP status code to check if there was an error.
So if you just throw a Java exception on your server side code but then the HTTP response doesn't have a 500 status code jQuery (or in this case probably the XMLHttpRequest object) will just assume that everything was fine.
I'm saying this because I had a similar problem in ASP.NET where I was throwing something like a ArgumentException("Don't know what to do...") but the error handler wasn't firing.
I then set the Response.StatusCode to either 500 or 200 whether I had an error or not.
jQuery.parseJSON is useful for success and error.
$.ajax({
url: "controller/action",
type: 'POST',
success: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(jqXHR.responseText);
notify(data.toString());
notify(textStatus.toString());
},
error: function (data, textStatus, jqXHR) { notify(textStatus); }
});
$("#save").click(function(){
$("#save").ajaxError(function(event,xhr,settings,error){
$(this).html{'error: ' (xhr ?xhr.status : '')+ ' ' + (error ? error:'unknown') + 'page: '+settings.url);
});
});
Throw a new exception on server using:
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
I believe that the StatusDescription is returned to the Ajax call...
Example:
Try
Dim file As String = Request.QueryString("file")
If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist")
Dim sTmpFolder As String = "Temp\" & Session.SessionID.ToString()
sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder)
file = IO.Path.Combine(sTmpFolder, file)
If IO.File.Exists(file) Then
IO.File.Delete(file)
End If
Catch ex As Exception
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
End Try
Although it has been many years since this question is asked, I still don't find xhr.responseText as the answer I was looking for. It returned me string in the following format:
"{"error":true,"message":"The user name or password is incorrect"}"
which I definitely don't want to show to the users. What I was looking for is something like below:
alert(xhr.responseJSON.message);
xhr.responseJSON.message gives me the exact message from the Json Object which can be shown to the users.
$("#fmlogin").submit(function(){
$("#fmlogin").ajaxError(function(event,xhr,settings,error){
$("#loading").fadeOut('fast');
$("#showdata").fadeIn('slow');
$("#showdata").html('Error please, try again later or reload the Page. Reason: ' + xhr.status);
setTimeout(function() {$("#showdata").fadeOut({"opacity":"0"})} , 5500 + 1000); // delays 1 sec after the previous one
});
});
If there is any form is submit with validate
simply use the rest of the code
$("#fmlogin").validate({...
...
...
});
First we need to set <serviceDebug includeExceptionDetailInFaults="True" /> in web.config:
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
**<serviceDebug includeExceptionDetailInFaults="true" />**
</behavior>
</serviceBehaviors>
In addition to that at jquery level in error part you need to parse error response that contains exception like:
.error(function (response, q, t) {
var r = jQuery.parseJSON(response.responseText);
});
Then using r.Message you can actully show exception text.
Check complete code: http://www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html
In my case, I just removed HTTP VERB from controller.
**//[HttpPost]** ---- just removed this verb
public JsonResult CascadeDpGetProduct(long categoryId)
{
List<ProductModel> list = new List<ProductModel>();
list = dp.DpProductBasedOnCategoryandQty(categoryId);
return Json(new SelectList(list, "Value", "Text", JsonRequestBehavior.AllowGet));
}

File Upload using JQuery Ajax with Struts1

My requirement is to submit a HTML form (Including File Type and Text Type) using AJAX call, I am using Struts-1 at the server side to parse the http request. Below is the code i have wrote, but its giving me exception when i try to print the name of the file.
JavaScript Code :-
function saveUpdateRfc(formId) {
console.log("Enter in Upload Script");
var formData = new FormData();
formData.append("file",formId.files[0]);
console.log(formData);
$.ajax({
url : "AddRfc.do",
type : "POST",
data : formData,
async: false,
cache: false,
mimeType:"multipart/form-data",
contentType: false,
processData: false,
success : function(result) {
if (result.result == "success") {
console.log("Rfc Added");
} else {
bootbox
.alert("Some Error Occured While Opening this Rfc. Please refresh the page and try again.If this Problem Persists, please report it to dev team.");
}
},
error : function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
bootbox
.alert("Some Error Occured While Opening this Rfc. Please refresh the page and try again.If this Problem Persists, please report it to dev team.");
},
complete : function() {
}
});
}
At Server Side, Here is the java code to get the file from the form.
RfcLogBean log = new RfcLogBean();
log = (RfcLogBean) form;
FormFile uploadedTakeoffSheet = log.getMyFile();
System.out.println("======= " +uploadedTakeoffSheet.getFileName());
System.out.println("======= " +uploadedTakeoffSheet.getContentType());
Can someone please help.!!

Categories

Resources