only http status been caught and not the JSON error response - react-native

The backend API responds with HTTP Status 400 and error messages as follows:
{detail: 'msg'}
It works well on web portal but with the following code, I can't read the response data:
try {
let res = await axios.post(APIS.START.LOGIN, loginData);
} catch (e) {
console.log(69, e);
}

You can access the body of the failed request by referencing e.response.data.
Simply replace console.log(69, e) with console.log(69, e.response.data)

Related

Why is Axios sending an extra 204 preflight request with my POST request?

Whenever I send a POST request using Vue.js (3.x), an additional request to the same URL is being made with HTTP status code 204 & type of "preflight".
What is this preflight request and how can I fix it so it isn't sent as a duplicate?
Register.vue
async submit() {
this.button = true;
try {
const response = await axios.post(`register`, this.form);
if(response.data.success == false)
{
console.log(response.data.message);
}
else
{
this.$router.push('/');
}
}
catch (error)
{
let { errors } = error.response.data;
this.button = false;
this.errors = {};
Object.keys(errors).forEach(element => {
this.errors[element] = errors[element][0];
});
}
},
This is not an issue and is controlled by the browser by design.
It is not something Axios or any other HTTP client decides to send.
A preflight request is a CORS OPTIONS request & are automatically sent by browsers specifically to check if the server would support the call you are trying to make in terms of method, headers and origin.
You can safely ignore the requests if they do not fail as that means that the server will not be rejecting your request on the basis of the aforementioned factors.
Your issue relates to the endpoint not existing as you are getting a 404 Not Found error - check to see if the endpoint exists or if you are calling it correctly.

Workbox BackgroundSyncPlugin _ Failed Request _ Notifications

i have a pwa who works fine. I make it with workbox.
But i want to try something.
I want to push notification when : the request ( who was hold in IndexeDB -> thanks of BackgroundSyncPlugin ) have an error ( like Error 500 ). The request send, is not the probleme of BackgroundSyncPlugin, but a probleme with my HTTP request. And i want to warn user that the request wasn't work
here a part of my service worker :
const bgSyncPlugin = new BackgroundSyncPlugin('myQueueName', {
maxRetentionTime: 0.1 * 60, // mins,
onSync: async({ queue }) => {
let entry;
while ((entry = await queue.shiftRequest())) {
try {
await fetch(entry.request);
console.error("Replay successful for request", entry.request);
} catch (error) {
console.error("Replay failed for request", entry.request, error);
// Put the entry back in the queue and re-throw the error:
await queue.unshiftRequest(entry);
throw error;
}
}
console.log("Replay complete!");
showNotification();
}
});
registerRoute(
/http:\/\/localhost:8000/,
new NetworkFirst({
plugins: [bgSyncPlugin]
}),
'POST'
);
I just want to know the status code of my request
Any help :)
Edit : i want to get Body in header2
You should be able to change this line:
await fetch(entry.request);
to
const response = await fetch(entry.request);
// Check response.status, and do something, e.g. throw an
// Error when it's above 500:
if (response.status > 500) {
// Throwing an Error will trigger a retry.
throw new Error('Status: ' + response.status);
}
// This assumes that your response from the server is JSON,
// and has an error field which might be set if the request
// failed for some reason, regardless of the HTTP status code.
const responseJSON = await response.json();
if (responseJSON.error) {
throw new Error('Failed request: ' + responseJSON.error);
}

Unbale to prevent PROPFIND http-method from servelt filter

I have made a filter and register on web.xml
when i am trying to filter http request of PROPFIND its throwing 500 Internal server error . this code works fine for any other http-methods. I want to have 405 in response code
if (httpRequest.getMethod()==”PROPFIND”) {
HttpServletResponse respProp = (HttpServletResponse) response;
respProp.sendError(405);
chain.doFilter(request, respProp);
} else {
chain.doFilter(request, response);
error i am getting
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:462)
at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:673)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
Instead of sending error i have sent 405 as response and my problem got solved
if (httpRequest.getMethod()==”PROPFIND”) {
HttpServletResponse resp = (HttpServletResponse) response;
resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
} else {
chain.doFilter(request, response);
}

Log middle-ware gets 200 response code when it is actually a 500

I am working on a ASP.Net Core Web API project and I want to log all the requests and 500 server errors.
I used custom middleware to log requests, and it is defined in the startup.cs as:
app.UseMiddleware<logMiddleware>();
I also defined an Exception handler to capture server errors in the startup.cs:
app.UseExceptionHandler(builder => {
builder.Run(async context => {
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null) {
logService logger = new logService(conf);
await logger.logError(error, context);
}
});
});
I keep the request information in error logs, so I don't need to save the request log when the response code is 500, so I added a check into request log function to filter errors:
public async Task logRequestAsync(HttpContext context) {
if (context.Response.StatusCode != 500) {
//do things
}
}
The problem is the Response.StatusCode returns as 200 instead of 500. Probably it runs before the API call's function is completed and the server error happens later in the runtime.
Is there a way to move the "request log" process to the point where the response is created instead of the beginning of the API request?

ionic 2: http get request not working (proxy added)

I'm using Http from #angular/http to send GET requests, but the server is not receiving the request. The generated urls are correct because when I log them and open them in browser (I've tried all of Chrome, Firefox and Safari), the server does receive these requests.
This is how I am doing this:
let logButtonUrl = this.urlGenerator.generateTiramisuUrlTemp(this.servletPath,
argMap);
console.log("logButtonUrl:"+logButtonUrl);
return this.http.get(logButtonUrl).map(this.writeSuccess);
Function writeSuccess:
private writeSuccess(res: Response) {
let body = res.json();
let rows_affected = body.data[0].rowsAffected;
if (rows_affected == "1") {
return true;
} else {
return false;
}
}
I got no error message in browser console, so it's probably not because of the CORS issue discussed here:
http://blog.ionic.io/handling-cors-issues-in-ionic/
I also tried using a proxy. I added this in ionic.config.json:
{
"path": "/backendTemp",
proxyUrl": "http://128.237.217.70:8080" /*the ip address of the target server*/
}
And replace the ip address in my generated urls with "/backendTemp". Still not working.
Any suggestions/thoughts on this? Thanks a lot!
Use the $http (https://docs.angularjs.org/api/ng/service/$http):
.controller('RequestCtrl', function ($http) {
$http({
method: 'GET',
url: 'http://128.237.217.70:8080/backendTemp'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});