Axios XMLHttpRequest - Network error on body exceeding a certain size - reactjs

I'm trying to POST a file as a base64 string to my API from a react app using axios. Whenever the file seems to exceed a certain (small ~150ko) size, the request is not sent and axios/xhr throws a Network error:
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
Any ideas?

It seems that basic POST requests using axios are capped in there file size. Using multipart form data for those uploads (populating a form with my file) seems to solve the pb
Source
But ultimately we moved to uploading directly to our AWS/S3 using a signed uri provided by our backend.

The problem is your type: of your file might not be valid one as per the MIME type. please check in your console
There might also be the problem of repeating the baseURL which means NETWORK_ERROR 404 NOT FOUND like of.. so please see the example below
let formData = new FormData();
formData.append("files", {
uri: payload.uri,
name: payload.name,
type: `payload.type?payload.type:image/${fileExt}` //this should be a valid Mime type
});
axios.post(`v2/upload_comment_file`, formData, {
headers: {
...(await HeaderData()),
"Content-Type": "multipart/form-data",
},
});
find mime type might get lil tricky for some image and doc picker lib like expo-doc-picker in ver 35.. please try react-native-mime-types https://www.npmjs.com/package/react-native-mime-types which helped me out and can help you too

Related

Cypress cy.request returns 404

I am using Cypress with react and node express server. I am trying to build a test that starts by calling cy.request with post method in order to initialize the state of the app for this particular test, but the response is always 404 as the following
Error:
CypressError: cy.request() failed on:
mysite.net
The response we received from your web server was:
404: Not Found
This was considered a failure because the status code was not '2xx' or '3xx'.
If you do not want status codes to cause failures pass the option: 'failOnStatusCode: false'
The request does work in prod/dev (status 200) but in cypress it always returns 404 as mentioned. I also checked the data structure of the request and it seems ok.
I am using the same route for all, the only difference is the method I use:
dev/prod: standard fetch API call seats under an apiHandler function.
Cypress: cy.request() method
My code:
cy.request({
method: 'POST',
url: `auth/login/example-url`,
failOnStatusCode: false,
form: true,
body: {
arrival: '2021-12-01T17:23',
departure: '2021-12-01T15:23',
destination: 'New York',
origin: 'Washington DC',
},
})
Thanks ahead for your help:)
when Browser: send request header and response status code OK
Using cy.visit(): response status code Not Found
So the problem is the Request Headers, you better check it, and set Headers in cy.visit() to look like Browser Headers. you'll receive the status code OK.

Problem with sendFile method and CDN Services

It seems the service its returning 400 and Error when parsing request output when the files are kinda big (Well not at all, because i'm trying to upload a 505kb .zip and its returning me an error), any kind of solution about this? Seems to be a random stuff because i upload a .pdf with a size of lets say 244KB and it returns error and then i try to upload a pdf with a size of 300kb and it goes fine, seems the CDN endpoint is having a strange behaviour, its also me happening with the images but not with the same frequency as the files.
Anyone have any kind of fix for this or idea why its happening?
I tried used postman and nodejs code and the results are always the same
try {
const response = await channel.sendFile(fs.createReadStream('file.pdf'),'file.pdf');
console.log(response);
} catch(e) {
console.log(e)
}
}
The process is returning the following
{ FetchError: invalid json response body at https://chat-us-east-1.stream-io-api.com/channels/messaging/XXXXXXX/file?api_key=XXXXXX reason: Unexpected token E in JSON at position 0
at /Users/user/Desktop/react-stream-chat-nodejs/node_modules/node-fetch/lib/index.js:272:32
at process._tickCallback (internal/process/next_tick.js:68:7)
message:
'invalid json response body at https://chat-us-east-1.stream-io-api.com/channels/messaging/XXXXXX/file?api_key=XXXXXX reason: Unexpected token E in JSON at position 0',
type: 'invalid-json' }

Angular $http.post returns 404 error

I am using angular JS to send some data to Payment Gateway.
Syntax for curl to send data as per documentation is:
curl https://www.mybank.co.uk/3dsecure
-H "Content-type: application/x-www-form-urlencoded"
-X POST
-d 'TermUrl=https://www.yourmerchantsite.co.uk/3DSecureConfirmation&PaReq=value-of-oneTime3DsToken&MD=merchantdatavalue'
However when I am doing it in Angular :
$http({
method: 'POST',
url: 'url',
headers: {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html'
},
data: $.param({TermUrl: obj.TermUrl ,Pareq: obj.Pareq }),
})
I am getting error
Possibly unhandled rejection: {"data":"<html><head><title>400 Bad
Request</title></head><body><h1>Bad Request</h1></body>
</html>","status":400,"config":
{"method":"POST","transformRequest":[null],"transformResponse":
[null],"jsonpCallbackParam":"callback","url":"payement gatway
url","headers":{"Content-Type":"application/x-www-form-urlencoded",
"Accept":"text/html,application/xhtml+xml"},"data":"TermUrl=url&Pare
q=value"},"statusText":"Bad Request","xhrStatus":"complete"}
Kindly suggest how to proceed with this one ?
First of all, you are experiencing a 400 Bad Request (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400) and not a 404 Not Found.
It usually means that you are not sending the right data to the server and the API is expecting some specific parameters (from the body usually).
Check the API, look at every parameter required from it - their types and how they should be sent (body param? query string? etc...).
You can use your browser network tab or tools like Postman to see what you are actually sending to the server and if it matches what the server is expecting you to send.
Check out 3D Secure's API reference, you should get back a detailed error code beside the http status code:
https://developer.paysafe.com/en/3d-secure/api/#/introduction/error-summary/common-errors
It should be easily debuggable.

Can't get any response back while calling service through frisbyJS

The code I am using is:
var frisby = require('frisby');
frisby.create('Get paf data')
.get('https://services.....')
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.toss();
The error I get while running it from CLI using
jasmine-node EndpointTest_spec.js
The error I get is:
Error: Expected 500 to equal 200
Error: Header 'content-type' not present in HTTP response
So do I need to first load my website and call services through my application and then run frisby ?
But then it defeats the purpose of just making a quick check for all the endpoints used in application without running it.
You are calling request with https:// which may be secure server so use
{ strictSSL: false} in your get method .get('https://services.....',{ strictSSL: false}). It will solve your problem.
var frisby = require('frisby');
frisby.create('Get paf data')
.get('https://services.....',{ strictSSL: false})
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.toss();

NetworkError: 405 Method Not Allowed AngularJS REST

In AngularJS, I had the following function, which worked fine:
$http.get( "fruits.json" ).success( $scope.handleLoaded );
Now I would like to change this from a file to a url (that returns json using some sweet Laravel 4):
$http.get( "http://localhost/fruitapp/fruits").success( $scope.handleLoaded );
The error I get is:
"NetworkError: 405 Method Not Allowed - http://localhost/fruitapp/fruits"
What's the problem? Is it because fruit.json was "local" and localhost is not?
From w3:
10.4.6 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource
identified by the Request-URI. The response MUST include an Allow header
containing a list of valid methods for the requested resource.
It means the for the URL: http://localhost/fruitapp/fruits The server is responding that the GET method isn't allowed. Is it a POST or PUT?
The angular js version you are using would be <= 1.2.9.
If Yes, try this.
return $http({
url: 'http://localhost/fruitapp/fruits',
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
I had a similar issue with my SpringBoot project, I was getting the same error in the browser console but I saw a different error message when I looked at the back-end log, It was throwing this error: "org.springframework.web.HttpRequestMethodNotSupportedException, message=Request method 'DELETE' not supported " It turned out that I was missing the {id} parameter in the back-end controller:
** Wrong code :**
#RequestMapping(value="books",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
** Correct code :**
#RequestMapping(value="books/{id}",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
For me, it was the server not being configured for CORS.
Here is how I did it on Azure: CORS enabling on Azure
I hope something similar works with your server, too.
I also found a proposal how to configure CORS on the web.config, but no guarantee: configure CORS in the web.config. In general, there is a preflight request to your server, and if you did a cross-origin request (that is from another url than your server has), you need to allow all origins on your server (Access-Control-Allow-Origin *).

Resources