My API makes multiple requests to the server - fetch

I'm not sure why, I'll press the button once, and I'll get 4 log events that are all the same except for the timestamp. Is there a way for me to prevent the multiple API calls or should I see if I can merge these multiple log events (stored as objects) in my database.
This is what my fetch request looks like:
fetch(apiUrl + "/api/first/registration", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: data.data,
}),
On my server side I immediately send a res.status(200) if it's successful.
Should I try Axios instead? Would that fix the problem?

Related

Why is a .net core controller Post method not accepting the anti forgery token?

I’m trying to do a POST using an API call for a form using a reactive framework (Vue 3 in my case). I’m using .net 6.0. It is not accepting the anti forgery request token. I’m putting it in the body of the request like it is for a traditional form submit.
The call in Javascript:
var token = $('input[name="__RequestVerificationToken"]').val();
var url = '/api/ShareAllocations';
$.ajax({
type: "POST",
url: url,
data: { fa: fa, '__RequestVerificationToken': token },
success: function (result) {
console.log(result)
},
complete: function (e) { },
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
In Fiddler, the textView of the input looks like this:
Fa= … (Json data)
__RequestVerificationToken=CfDJ8BSiPpdXlmRFvbl4LFJ0x7iHfmWBSdPblTwBjlLUq-We2oD60dKqBCYx4dUwXG5Gxprtl3lW2zzs4K8_iBf8eu0RQqOM928ANv1-16rcqizvYhUDFC5iaDo97wpqCsdFFxlmhiRaHW1zxhmEcwpYMrpZWBnzUbjGkTa-qUSs5GfuT2MwJGEWWYqyz7D95RRJVA
The API call returns a 200, but then the web page shows a 400 Bad Request.
From Fiddler:
143 200 HTTPS localhost:7164 /api/ShareAllocations
144 400 HTTPS localhost:7164 /FarmAllocation/Manage
For comparison purposes, I’m showing the body of a submit in .net core. The key value pair for the anti forgery token looks the same to me.
SENIOR_LIVING_FACILITIES.FACILITY_ID=0&SENIOR_LIVING_FACILITIES.FACILITY_NAME=n&SENIOR_LIVING_FACILITIES.ADDRESS=&SENIOR_LIVING_FACILITIES.CITY=&SENIOR_LIVING_FACILITIES.STATE=ME&SENIOR_LIVING_FACILITIES.ZIP=&SENIOR_LIVING_FACILITIES.CONTACT_NAME=&SENIOR_LIVING_FACILITIES.CONTACT_ROLE=&SENIOR_LIVING_FACILITIES.PHONE=&SENIOR_LIVING_FACILITIES.EMAIL=&__RequestVerificationToken=CfDJ8BSiPpdXlmRFvbl4LFJ0x7iHfmWBSdPblTwBjlLUq-We2oD60dKqBCYx4dUwXG5Gxprtl3lW2zzs4K8_iBf8eu0RQqOM928ANv1-16rcqizvYhUDFC5iaDo97wpqCsdFFxlmhiRaHW1zxhmEcwpYMrpZWBnzUbjGkTa-qUSs5GfuT2MwJGEWWYqyz7D95RRJVA
It turns out the post was working fine. Passing the token in the body of the message works fine. I had a side effect because of a submit button so the 400 bad request was not pertinent.

Where do ajax headers go when making a server call?

I am new to the web developer side and am trying to make sense of how AJAX headers work. We use .NET Framework MVC project with some methods on the controller that are called by our views to get some data.
Example of our view ajax call to the server:
jQuery.ajax({
type: "POST",
data: { "ElementPath": ElementPath },
dataType: "json",
headers: {
'VerificationToken': forgeryId
},
url: "" + BasePath + "/Home/GetAttributes",
});
The GetAttributes method on the server accepts a string as a parameter and returns a string of JSON objects. When I put a breakpoint on the method, the only thing I see in the string parameter is the contents of ElementPath, and nothing to do with headers. In my mind the server method would also have the contents of forgeryId. So what exactly is using the headers and how?

NextJS, fetch, multipart/form-data, missing boundary

I've faced with issue while proxy http request with multipart form data by NextJS. I have to send file from a client fide to next js, after that - to FastApi service.
The problem was:
fetch("https://127.0.0.1:3000/api/newfile", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: new FormData(form)
});
headers request: "Content-Type: multipart/form-data"
In order for NextJS API to parse the file, you need a header with boundary
Something like this:
multipart/form-data; boundary=----< generate boundary >
For a long time I could not figure out how to get it.
There is an exit. It is necessary not to fill in "Content-Type".
And then the browser itself will generate this header by passing the form-data.
For example:
fetch("https://127.0.0.1:3000/api/newfile", {
method: "POST",
headers: {},
body: new FormData(form)
});
I also noticed that the problem concerns fetch
When I used XMLHttpRequest I didn't face such problem.
Further, the header can easily be passed further to FastAPI
in API:
req.headers["content-type"]

NextJs - Use fetch() to make api call with POST method - always ERR_ABORTED 400

when I try to make api call with fetch() method and request type is POST, then I receive error in console: "POST ... ERR_ABORTED 400 (Bad request)"
btw. I have used 'no-cors' mode because api url is on different domain, I know that this is not best approach. For now I just want to make it to work and later I will deal with CORS issue that I have when mode is not set to 'no-cors'.
const res = await fetch(apiUrl, {
method: 'POST',
body: JSON.stringify({
sku: sku
}),
headers: {
'Authorization': 'Bearer ' + jwtToken,
'Content-Type': 'application/json'
},
mode: "no-cors"
});
What can be the cause why fetch() method always returns error, maybe something with the syntax? Both "sku" and "jwtToken" variables are set.
I tried it with postman and everything works fine, but when I try to make that api call inside nextjs then its not working.

Getting 401 on API but working with postMan

I have this API:
const url = url;
const headers = new Headers({
"Content-Type": "application/json",
"Accept": "application/json", // change to application/javascript for jsonp
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": true,
"access_token": accessToken,
"id_token": idToken,
});
const options = {
method: "GET",
headers: headers,
credentials: "same-origin",
mode: "no-cors"
};
fetch(url, options)
.then(function(response) {
console.log('-working: ',response.json());
})
.catch(function(error) {
console.log('-error: ',error);
});
Having the same API on postMan this works like a charm there but on my code I always get 401 (Unauthorized).
Also if I remove "no-cors" I get a 401 plus CORS issue
I was having the same issue.
My senior said, that CORS is not safe, so first compare the headers of both the requests.
I would suggest you use Wireshark to see the the header that is being sent from both the requests.
Steps(step 3 and 4 is for conveniently spotting your requests):
Install Wireshark.
Select the network connection that you are using for the calls(for eg, select the Wifi if you are using it)
There will be many requests and responses, close extra applications.
Usually the requests are in green color, once you spot your request, copy the destination address and use the filter on top by
typing ip.dst==52.187.182.185 by putting the destination address.
Tap on your request made by postman and by your call.
Compare both the headers.
In my case, I was calling the API from my react native app, and the header parameter was getting converted into lowercase automatically.
So, to correct it, I made the parameter in lowercase in backend server.
Play "Spot the difference" between the two windows and find yours.
If this doesn't work, go with setting up CORS.
CORS needed to be added as an additional header on the back end

Resources