Javascript fetch POST request formdata size limitation CORS error? [closed] - api

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm attempting to make a pretty straightforward fetch request to one of our business' APIs (back end running .NET Core 3.1/ASP Core MVC), and it's giving me an inconsistent result. If the length of the token value passed via a formdata field is greater than about 1000 characters, the request gets stopped with a CORS error (the pretty standard "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource"), but below that length the request goes through without issue. Running on Chrome or on Firefox both give me a CORS error about missing this header value. There aren't any specific limits on input size set within the API itself or the IIS server it's running on, so I'm at a loss for what might be going on.
I'm assuming this is one of those times when a CORS error is really just masking something else going on. Is there something obvious I'm overlooking?
obj = {
data: {
idToken: "A".repeat(1200) // just for testing purposes
}
};
str = JSON.stringify(obj);
const fd = new FormData();
fd.append("token", str);
const BaseURL = "https://XXXX";
const url = `${BaseURL}/api/YYY/getLocations`;
fetch(url, {
method: 'post',
body: fd,
})
.then...

It turned out that the network appliance that handled requests to all of our externally visible API's was imposing a strict size limit on all incoming requests. Once that was lifted to a higher level, everything worked as expected.

Related

How to change the http client used by pouchDB?

I am using PouchDB and CouchDB in an ionic application. While I can successfully sync local and remote databases on Chrome and Android, I get unauthorized error on Safari / iOS when I run the sync command. Below is a simplified version of my database service provider.
import PouchDB from 'pouchdb';
import PouchDBAuthentication from 'pouchdb-authentication';
#Injectable()
export class CouchDbServiceProvider {
private db: any;
private remote: any;
constructor() {
PouchDB.plugin(PouchDBAuthentication);
this.db = new PouchDB('localdb', {skip_setup: true});
}
...
login(credentials) {
let couchDBurl = 'URL of my couchDB database';
this.remote = new PouchDB(couchDBurl);
this.remote.logIn(credentials.username, credentials.password, function (err, response) {
if (err) { concole.log('login error') }
else {
let options = { live: true, retry: true, continuous: true };
this.db.sync(this.remote, options).on('error', (err_) => { console.log('sync error')});
}
})
}
...
}
In the code above, this.remote.logIn(...) is successful but this.db.sync(...) fails. I have checked the requests via the network tab of developer tools and I believe the issue is that the cookie that's retruned in the response header of this.remote.logIn(...) is not used by the subsequent calls (thus the unauthorized error). The issue is fixed once third-party cookies are enabled on Safari, which is not an option on iOS.
How can I fix this problem?
One potential solution I'm considering is overriding fetch to use native http client (i.e., an instance of HTTP from #ionic-native/http). It seems modifying http clients is a possibility (e.g., according to this conversation) but I'm not sure how to achieve that.
Changing the HTTP plumbing sounds like a really bad idea - time cost, mainly - unless you just absolutely have to use sessions/cookies...If you don't, read on.
as noted here regarding pouchDB Security, I tried using pouchdb-authentication when it was actively maintained and went another route due to multiple issues (I don't recall specifics, it was 6 years ago).
Do note the last commit to pouchdb-authentication seems to be 3 years ago. Although inactivity is not an negative indicator on the surface - a project may have simply reached a solid conclusion - installing pouchdb-authentication yields this
found 6 vulnerabilities (2 moderate, 3 high, 1 critical)
That plus the lack of love given to plugin over the last few years makes for a dangerous technical debt to add for a new project.
If possible simply send credentials using the auth option when creating (or opening) a remote database, e.g.
const credentials = { username: 'foo', passwd: 'bar' };
this.remote = new PouchDB(couchDBurl, { auth: credentials });
I don't recall why but I wrote code that is in essence what follows below, and have reused it ad nauseum because it just works with the fetch option
const user = { name: 'foo', pass: 'bar' };
const options = { fetch: function (url, opts) {
opts.headers.set('Authorization', 'Basic ' + window.btoa(user.name+':'+user.pass));
return PouchDB.fetch(url, opts);
}
};
this.remote = new PouchDB(couchDBurl, options);
I believe I chose this approach due to the nature of my authentication workflow discussed in the first link of this answer.
I agree with #RamblinRose that you might have to include the headers manually when you define the PouchDB object.
I myself have found a solution when working with JWTs that need to be included in the header for sync purposes.
See this answer. Note: RxDB uses PouchDB under the hood so it's applicable to this situation. It helped me sync, hope it does you too!
https://stackoverflow.com/a/64503760/5012227
One potential solution I'm considering is overriding fetch to use native http client (i.e., an instance of HTTP from #ionic-native/http). It seems modifying http clients is a possibility (e.g., according to this conversation) but I'm not sure how to achieve that.
Yes, this is a possible option - especially if you want to use SSL pinning which will only work with native requests. And you don't need to worry about CORS (apart from ionic serve).
You can achieve this e.g. by taking an existing fetch - polyfill and modifying it s.t. it uses the http plugin instead of xhr. And since you'll only deal with JSON when interacting with the CouchDB, you can throw away most of the polyfill.

Multi threaded access requested by thread Thread[pool-2-thread-1,5,main] but is not allowed for language(s) js [duplicate]

This question already has answers here:
Karate - Multi threaded access requested - issue
(2 answers)
Closed 1 year ago.
I'm converting about 2800 tests from Karate 0.9.6 to Karate 1.1.0. While going through the breaking changes and refactoring the existing tests I'm encountering a lot of tests randomly failing due to the error:
Multi threaded access requested by thread Thread[pool-2-thread-1,5,main] but is not allowed for language(s) js.
These are for different reasons all over the place. Most are from Background steps but not all. Here are a few cases that fail:
* configure headers = { cache-control: 'no-cache' , Accept: 'application/fhir+json' }
* def authToken = callonce read('classpath:com/company/tests/token/AuthToken.feature')
And header Access-Control-Request-Headers = 'Content-Type'
I tried to create a project to duplicate the issue but it seems random. Are there known issues with this?
I really hope that it is this issue: https://github.com/intuit/karate/issues/1725
Which will be easy to confirm, just upgrade to 1.2.0.RC1
If that doesn't work, that will be extremely bad news and you will have to submit a way to replicate.
And do note that the new JS engine doesn't like Java or JS functions being passed around in callSingle() or callonce: https://github.com/intuit/karate#karatecallsingle (see the paragraph that begins with IMPORTANT:)

Does Karate Support displaying the assertions or failures in the html Report for Server side scenario of incoming API requests to a mock server? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
This might be a dumb question or may be already answered but i wasnt able to find any answers for this :
I have a requirement of testing a Micro Service that sends out an API request to a particular endpoint or a Consumer. I was able to successfully write the mocks using karate and send back response on required filter criteria and validations happening inside the "server-side" scenario.
If any assertion fails it does log that server-side scenario failed.
I wanted to know how i can add these to a report ( i currently use the cucumber reporting which can be integrated with Karate) and fail a test if any server side scenario fails?
Any help would be appreciated.
Great question, this is an unusual requirement - but you can be super-creative with Karate mocks.
Remember - a Karate mock is a legitimate REST server, so all you need to do is add one more request "route". You already know that you can "collect" data into global variables defined in the Background. So something like this:
Background:
* def errors = []
Scenario: pathMatches('/myapi')
* def result = karate.match("request == { foo: 'bar' }")
* if (!result.pass) errors.add(result)
* def response = { some: 'response' }
Scenario: pathMatches('/mytest')
* def response = errors
Now at the end of your test, just call the additional /mytest API and you get a nice JSON array of all errors.

Reachability Module

Sorry for all the questions regarding this app. I have been struggling on coding this app for days.
As you might have seen from my previous questions, I am currently trying to build an app that checks if a website server is up or down.
I have read many old stack overflow questions and they say to use the reachability module. When I go to the apple reachability module, it seems to be outdated.
Does anyone have any other solutions to this app? My goal is to ask the user to enter how many ever websites they want and then the app checks if they are up or down.
make a URL request and then check for response . If response code is 503 then the server is down. you can see the list of server responses HERE and below code to check for responses
let url = URL(string: "Your Server URL")
let task = URLSession.shared.dataTask(with: url!) { _, response, _ in
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.statusCode) // if the response code is 503 then the server is down
}
}
task.resume()

What is difference between axios and fetch in react native? [duplicate]

This question already has answers here:
What is difference between Axios and Fetch?
(11 answers)
Closed 3 years ago.
I m new in a react native so please can you explain more about in this question?
Overall they are very similar the only difference is that axios is alittle bit more developed. Some benefits of axios:
Transformers: allow performing transforms on data before request is made or after response is received
Interceptors: allow you to alter the request or response entirely (headers as well). also perform async operations before request is made or before Promise settles
Built-in XSRF protection
for more info you can check this discussion https://github.com/axios/axios/issues/314