I am eager to use the new fetch method and I understand it can be used for all http method calls to a Rest endpoint.
So I have the following very simple API endpoint which I know works, get and post requests work. The issue I am having is getting the post request to work on the fetch method.
My code for the fetch method is
var ingredient = {
'name': 'Salt',
}; // a JSON object used as the body for the post request
fetch('http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
{
method: "POST",
body: JSON.stringify( ingredient )
})
.then(function(res){ console.log( 'Data posted') })
I then get the following error message. 422 (Unprocessable Entity)
If on the other hand I do something very similar but this time using the classic jQuery ajax post method it works.
$.ajax({
url: 'http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
type: 'POST',
data: 'name=Salt', // or $('#myform').serializeArray()
success: function() { console.log('Data posted'); }
});
Any help here would be appreciated, it feels like I am missing something small here, and documentation on fetch method is scant on the web.
The two request sends two different post bodies one is application/x-www-form-urlencoded (jQuery) and the other is application/json.
You'll have to change the fetch call to send the same type of data as the $.ajax call.
You may have to explicitly set the content type in the fetch request.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var searchParams = new URLSearchParams();
searchParams.append("name", "Salt");
fetch('http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
{
method: "POST",
headers: myHeaders,
body: searchParams
})
.then(function(res){ console.log( 'Data posted') })
Related
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;
}
I'm attempting to make a POST request to a URL on my website in JavaScript.
I previously was using jQuery's $.post() function which sends the data object correctly as is, but when attempting to switch to the built-in Fetch() method, I am struggling to send the data in the same form as the jQuery method.
I have the following JavaScript object:
let requestBody = {
username: document.getElementById('username').value,
password: document.getElementById('password').value,
}
and I'm attempting to make a POST request to the URL '/user/login'.
The following jQuery method works:
$.post('/user/login', requestBody);
But when trying with the Fetch method:
fetch(new Request('/user/login'), { method: 'POST', body: requestBody })
I do not see any form body in the Chrome developer tools.
If I try to stringify the requestBody object:
fetch(new Request('/user/login'), { method: 'POST', body: JSON.stringify(requestBody) })
You can see I do not have any data under Form Data as I do with jQuery, and instead it is under Request Payload. The problem with this, is that it is incompatable with my already written backend code.
How can I POST a JavaScript object to a URL with Fetch() just as a jQuery $.post() would?
what you need is to use FormData instead of JSON representation
here is how to do it, basically it looks like this:
var formData = new FormData();
formData.append("username", document.getElementById('username').value);
formData.append("password", document.getElementById('password').value);
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.
I'm pretty new on using APIs and I am having a problem with Instagram's new api.
For a dislike function, the documentation states to use a delete method, but I keep getting an error: XMLHttpRequest cannot load URL. Response for preflight has invalid HTTP status code 405.
Funny thing is that when I try the exact same thing with curl, it works.
For example, this is a working method: curl -X DELETE https://api.instagram.com/v1/media/{media-id}/likes?access_token=ACCESS_TOKEN
But if I try to use it with javascript
if( user_has_liked ){
$.ajax({
crossDomain: true,
url: "https://api.instagram.com/v1/media/"+ photoId +"/likes?access_token=" + ACCESS_TOKEN,
method: 'DELETE',
success: function(data){
response = data.data;
document.getElementById(photoId).className = "fa fa-heart-o";
document.getElementById(photoId).onClick = function(){
subscribe(photoId, false);
}
}
});
}
All I get is a 405 error.
I've tried enabling CORS but it seem to work either
I would be really grateful if anybody could give me a hand on this.
Many thanks!
I solved this issue sending a request utilizing the POST method and "delete" like a parameter. Then it is looking like this:
$.ajax({
url: "https://api.instagram.com/v1/media/"+ photoId +"/likes?access_token=" + ACCESS_TOKEN,
method: 'POST',
data: {_method: 'delete'},
success: function(data){
console.log(data);
}
});
Font: http://laravel.io/forum/02-20-2014-sending-a-delete-request-via-ajax
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.