Fetch API call causes new Asp.net session - javascript

I'm in the process of removing jQuery in one of my asp.net mvc projects in favor of using straight vanilla JS. Now that I've replaced $.ajax POST calls with Fetch API calls, each call triggers a new session on the server.
This has been driving me up the wall for the past few days, and I've narrowed it down to specifically this switch from using jQuery Ajax to Fetch API. My new Fetch API calls work perfectly otherwise, still performing the needed server-side work. The just trigger a new server session once they return.
Obviously, this is a major issue, as my user session data keeps getting reset. Any idea as to why this happens? Or anyone know of any workarounds, while not having to revert back to using jQuery?
My previous 'jQuery'-based POST call:
Post(route, data) {
$.ajax({
type: 'POST',
url: route,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8"
}).done((result, statusText, jqXHR) => {
return result;
});
}
My new 'Fetch API'-based call:
async Post(route, data) {
let response = await fetch(route, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify(data)
});
let result = await response.json();
return result;
}
In my Global.asax.cs:
protected void Session_Start(object o, EventArgs e) {
Debug.WriteLine("Session_Start");
HttpContext.Current.Session.Add("__MySessionData", new MySessionDataClass());
}
As I mentioned above, the Fetch API call works perfectly fine other than resetting my session, which I know from the Debug.WriteLine call. The jQuery Ajax call also works perfectly fine, and does not trigger a new session, however I'm trying to remove my dependency on jQuery.
Thoughts?

You're not passing in the ASP.NET_SessionId cookie with your custom request.
You are using fetch. By default it uses omit for the credentials. This means, as said on the MDN page:
By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).
JQuery does send cookies, but only those on the same domain.
AJAX calls only send Cookies if the url you're calling is on the same domain as your calling script.
Source
To fix this, you need to tell fetch to send cookies. From this post:
fetch('/something', { credentials: 'same-origin' }) // or 'include'

Figured out the issue with the help of #gunr2171, so self-answering in case anyone else comes across a similar issue.
Turns out that my new Fetch API call was not sending the current Asp.net session cookie with the request, so the server would start a new session thinking that one didn't exist yet. Tweaking the Fetch API call to include credentials: 'include' in the options allows it to send the current session cookie and the server will no longer create a new one after every call.
For reference, my new Fetch API call now looks like:
async Post(route, data) {
let response = await fetch(route, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
credentials: 'include',
body: JSON.stringify(data)
});
let result = await response.json();
return result;
}

Related

How to make POST request with javascript in a Chrome Extension?

I was wondering if there is anyway to make this:
<form action="http[://localhost/.../script.php" method="POST">
a regular call. I don't want it to run on form submit, but instead I wan't it to run when I call a function.
Would I use jQuery or AJAX?
You may use Fetch API on chrome to do so:
// building your form values
var data = new URLSearchParams();
data.set('var1', 'value 1');
data.set('var2', 'value 2');
// send to the endpoint
fetch("http://localhost/.../script.php", {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data
}).then(function(response) {
// check the response object for result
// ...
});
You can use ajax to call the the php function and store its response.
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
Make sure u include jquery CDN
You could use AJAX to post data to your PHP script, which will then run.
Note that jQuery and AJAX are not alternatives for each other.
AJAX is an asynchronous HTTP request (which is what you want).
jQuery is a javascript library which you can use to make AJAX calls.
I would take a look at https://api.jquery.com/jQuery.post/
This is a shorthand function for making an ajax POST request. E.g.:
function triggerMyPhpScript(data) {
$.post("http://localhost/.../script.php", data, function(responseData) {
// do something with the response of your script
});
}
I also like the Fetch answer from Koala Yeung. This will also work fine on modern browsers. Keep in mind that if you want to support ancient browsers (e.g. internet explorer), you need to implement feature detection and a fallback in case fetch is not supported by the browser.

Change a jquery ajax POST request into a fetch api POST

I have some json data that I have been posting to an API using $.ajax but I would like to update this to use the fetch API. However I seem to have it setup the Fetch API request ends up returning a 403 so I must be missing something but I can't work it out.
Ajax request:
$.ajax({
type: 'POST',
url: url,
data: {
'title': data.title,
'body': data.body,
'csrfmiddlewaretoken': csrf_token,
'request_json': true
},
success: function (data) {
console.log(data)
}
});
Fetch attempt (one of many):
let payload = {
'title': data.title,
'body': data.body,
'csrfmiddlewaretoken': csrf_token,
'request_json': true
}
let request = new Request(url, {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: JSON.stringify( payload )
});
fetch(request)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then((response) => response.json())
I have tried with various different headers, content encoding and sending the data as form data using:
let form_data = new FormData();
form_data.append( "json", JSON.stringify( payload ) );
let request = new Request(url, {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: form_data
});
...
Any help would be great and if you need any more info let me know
Thanks
To port an existing jQuery.ajax request to fetch, you need to consider that jQuery always includes cookies for you, but fetch does not.
Quoting MDN (emphasis mine):
Note that the fetch specification differs from jQuery.ajax() in mainly two ways that bear keeping in mind:
- The Promise returned from fetch() won’t reject on HTTP error status [ ... ]
- By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials header must be sent).
Edit: spec has changed since then, so this should no longer be a problem:
Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.
So the following (returning to original answer) only applies to "older" browsers.
Thanks David Richmond from comments :)
So you get 403 (Forbidden) because your API likely relies on cookies for authentication/authorization (even in your case, where you send a csrfmiddlewaretoken, the server-side framework might still expect a cookie with that -- guessing Django?).
To fix this, add credentials: "same-origin" to your Request (*), like so:
let request = new Request(url, {
method: 'post',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
(*) Valid options for credentials are:
omit: Never send cookies. This is the default (and your problem).
same-origin: Only send cookies if the URL is on the same origin as the calling script.
include: Always send cookies, even for cross-origin calls.
You say:
'Content-Type': 'application/x-www-form-urlencoded'
and
body: JSON.stringify( payload )
JSON Encoding is not the same thing as WWW Form Encoding!
You also tried
form_data.append( "json", JSON.stringify( payload ) );
FormData objects are converted to Multipart MIME.
Multipart MIME is also not the same as WWW Form Encoded data.
JSON nested inside Multipart MIME even less so.
This question describes how to convert an object (payload) into a Form Encoded string.

How to destroy the response before each http request using angular js?

I want to clear my http response before each request sending to API.
My Http request:
$http(
{
method: 'GET',
url: URI,
headers: { 'Content-Type': 'application/json' },
async: false
}).success(function (data) {
$('#processing').hide();
$scope.items = JSON.parse( angular.toJson(data));
$scope.header = $scope.items[0];
Could you please help me ,so that each time I will get new response?
Thanks
The response is probably cached by browser or something between your browser and server.
You can either try to prevent caching by adding header which tells the browser not the cache given response
Or
you can append unique timestamp to the URL, like this
var no_cache_url = URL + new Date().getTime()
If you are using some query string in your url then the code is slightly more complicated, but you will figure that out.

Angular.js ie ajax request issue

I have a problem with angular.js ajax call with IE. The first time I do the request, all is working good (I get the good result). But when I do an other ajax call (same request) without refreshing the page, the result look to be the same as the first call, even if it shouldn't be the same.
Here's how my request look like :
this.getemploye = function (isaftersave) {
$http({
url: 'Contact.svc/getemployee',
method: "GET"
}).success(function (data) {
//The data result is always the same with IE.
});
};
Note that I have no problem with Chrome and FireFox. The version of IE is 11.
IE will aggressively cache all ajax calls (actually pretty much everything). You will need to set the cache options on the HTTP response headers from your servers.
You will need to add the Cache-Control header to your ajax response sent from the server if you do not want it cached.
Cache-Control: no-cache, no-store
As an extra measure you should set cache:false in your $http call
$http.get('https://api.myapp.com/someresource', { cache: false });
If you haven't got access to modify the server you could always just append a random query string onto the url every time This will force IE to re-issue the request as it won't have seen that url before.
this.getemploye = function (isaftersave) {
$http({
url: 'Contact.svc/getemployee?nocache=' + new Date().toISOString(),
method: "GET"
}).success(function (data) {
});
};

Jquery ajax POST url getting changed and bad request returned

I am using a function from Spotify Playlist Creator in my file to send a POST request to the API to create a new playlist. The function works fine when i run the "Spotify Playlist Creator" code, with the POST request returning a response object with a new playlist id. But the same POST request returns "400 : Bad Request" when run from my code.
Other GET requests (user profile requests) are working fine (and hence i am guessng the authorization flow is successful and the access_token is valid.)
When i used the Chrome inspector, one thing that i noticed is that in the working app, the POST url is Request URL:https://api.spotify.com/v1/users/121856107/playlists
In my app it is Request URL:https://api.spotify.com/v1/users/121856107/playlists?{%22name%22:%22test_playlist%22,%22public%22:false}
Here the url has the data elements appended to it. Why is this happening? Any pointers ?
Below i have pasted the function which is behaving differently in two different sites.
Update: It appears that the POST request is somehow converted to OPTIONS. A quick search showed that this behaviour might be related to "Same origin policy".
How do i get my function to start working?
function createPlaylist(username, name, callback) {
var url = 'https://api.spotify.com/v1/users/' + username +
'/playlists';
$.ajax(url, {
method: 'POST',
data: JSON.stringify({
'name': name,
'public': false
}),
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + g_access_token,
'Content-Type': 'application/json'
},
success: function(r) {
console.log('create playlist response', r);
callback(r.id);
},
error: function(r) {
callback(null);
}
});
}

Categories