Using fetch with method post - ajax

I have a phonegap application that uses
$.ajax(
type: 'POST,
dataType:"json",
url: 'test.com'
data: { mail: 'bob#test.com' }
)
which i get in my glassfish server doing something like
HttpServletRequest request;
request.getParameter('mail');
I'm moving my application in react native so i'm doing
fetch('test.com', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ mail: 'bob#test.com' }),
})
but that doesn't work, my glassfish server doesn't get my parameters.
How should i do ?
It goes without saying that i don't want to make changes on the server side !

In your first example (using $.ajax()) you are not sending a JSON body. You are actually sending a query string. In your react example, you are sending a JSON body which would need to be handled differently by your server.
You will need to either change your server handler to actually accept JSON or you will have to send a query string with react which would look something like:
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: $.param({ mail: 'bob#test.com' }),
})
If you don't have access to jQuery you wouldn't be able to use $.param(). For this particular example, the query string you'd want to send would be
body: "mail=bob#test.com"
It is fairly straightforward to serialize data for a query string and creating a function that will do it pretty easy.
As a side note, in order to send a JSON body with an $.ajax() call, you would want to do something like this:
$.ajax(
type: 'POST,
dataType:"json",
url: 'test.com'
data: { mail: 'bob#test.com' }
contentType: "application/json",
)
Note the contentType parameter which actually tells jQuery how to format the body of the request

Related

Cypress using JSON fixture in body?

So based off Cypress request docs: https://docs.cypress.io/api/commands/request.html
It seems like I should be able to send a POST request with a JSON body pretty easily. So this is what I tried:
cy.fixture('test_create').as('create_test')
cy.request({
method: 'POST',
url: 'http://localhost:8080/widgets',
body: '#create_test',
headers: {
'Authorization': this.token,
'Content-Type': 'application/json;charset=UTF-8'
}
})
However when I look at the "commands" Cypress sends, it's sending the body as literally Body: #create_test
Is it not possible to use a fixture within the body of a POST request? I confirmed the fixture is loading correctly. I confirmed also it works when I paste the entire JSON inside of the body option....but that gets ugly really quick with large JSON bodys.
You get a literal because in the form cy.request(options), options is a plain JS object and unfortunately not parsed by Cypress to interpret the alias.
The request form cy.request(method, url, body) probably does allow an alias for the body param, since cy.route() allows it ref: Accessing Fixture Data
e.g the following should be valid, but does not allow setting headers
cy.fixture('test_create').as('create_test')
cy.request('POST', 'http://localhost:8080/widgets', '#create_test');
So, you can use then()
cy.fixture('test_create').then(myFixture => {
cy.request({
method: 'POST',
url: 'http://localhost:8080/widgets',
body: myFixture,
headers: {
'Authorization': this.token,
'Content-Type': 'application/json;charset=UTF-8'
}
})
});
or
cy.fixture('test_create').as('create_test');
... // some other code between
cy.get('#create_test').then(myFixture => { // retrieve the fixture from alias
cy.request({
method: 'POST',
url: 'http://localhost:8080/widgets',
body: myFixture,
headers: {
'Authorization': this.token,
'Content-Type': 'application/json;charset=UTF-8'
}
})
})

Ajax request what?

So I have a stupid question about this:
$.ajax({
type: "GET",
url: `URL`,
data: DO STUFF WITH WHAT I GOT FROM THE REQUEST???,
});
In ajax, when I make a get request from a URL, with the data: parameter am I giving a response that is data or is data the data I received from the request?
You can do something with the data in the success part of the ajax call:
$.ajax({
dataType: 'json',
url: url,
data: data,
success: success
});
In this case, a potential success callback would look like this:
function success(data) {
// do something with data, which is an object
}
or if there is no data to send:
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
success:function(data) {
handleData(data);
}
});
}
The main thing to understand here is that any AJAX call (any web request really) has two components: A request and a response. The actual $.ajax() function call is sending the request, and a callback function is provided to handle the response.
To illustrate:
$.ajax({
type: "GET", // request type
url: "http://www.example.com/someResource", // destination URL
data: { name: "David", location: "Boston" } // data to send
});
This would make a GET request to the specified URL, sending it the specified data. The response in this case is ignored, since no callback is provided. But you can provide one:
$.ajax({
type: "GET",
url: "http://www.example.com/someResource",
data: { name: "David", location: "Boston" }
}).done(function(response) {
// handle the response
});
The function which contains "handle the response" will be called by the system when the AJAX response is received from the server. The response variable (or whatever you want to call that variable, the name doesn't matter) will contain whatever the server sent in return. Which could be anything, really.

Is it possible to add multi media type to HTTP header?

I want to make a request have both JSON and file
My controller :
#Authorize(roles={UserType.ADMIN,UserType.SCHOOL_ADMIN})
#RequestMapping(value="import",method=RequestMethod.POST)
public List<AddUserResponse>importUserBundle(#RequestBody AddUserRequest test,#RequestParam(value="userCsv")MultipartFile[] userCsv)
And got error when making a request :
Content type
'multipart/form-data;boundary=----WebKitFormBoundary62tvsTfonhCQ6HSl;charset=UTF-8'
not supported
Is there any way to make a request with both multipart/form-data and application/json media type?
Your AJAX call should be like this:
$.ajax({
url: '/importUserBundle',
type: 'POST',
data: {
userCsv: FileToSend,
test: JsonData
},
dataType: 'json',
processData: false,
contentType: false,
success: function(data)
{
}
});
EDITED
processData:false Don't process the files
contentType:false Set content type to false as jQuery will tell
the server its a query string request.
Look at this for more info http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
Hope this will help

Extjs 4.2: How to send parameters properly in a Ext.Ajax.Request POST

I have to do a POST from my ExtJs script in order to delete something from my DB:
Ext.Ajax.request({
url: 'deleteRole.html',
method: 'POST',
headers: {'Content-Type': 'text/html'},
waitTitle: 'Connecting',
waitMsg: 'Sending data...',
params: {
"rolename" : rolename
},
scope:this,
success: received,
failure: function(){console.log('failure');}
});
when the post is sent i can see in the firebug the rolename in font but not as a param. I would like to show you another post (made with spring:form) relative to the user registration. If i inspect the post i can see the following:
(source: subirimagenes.com)
And i can get the parameters in my controller using #RequestParam.
But in the post that i have problems i can't see the parameters part, i can only see the Font(Fuente) part:
(source: subirimagenes.com)
As a consequence, my spring controller does not detect any parameter. Is it something wrong in my POST?
Thank you
The problem is that you are using the line headers: {'Content-Type': 'text/html'}, in your original question. This would set the content to text/html instead of the content being post data.
I solved it with the following code:
var rolename = 'myRol';
Ext.Ajax.request({
url: 'deleteRole.html',
method: 'POST',
params: {
rolename: rolename
},
success: received,
failure: function(){console.log('failure');}
});
I'm using this in a Sencha Touch app. I had to add an extra config called jsonData and make it true or else nothing is passed to my endpoint url.
Ext.Ajax.request({
url: endpoint,
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : {add: formattedAddress, lat: latitude},
jsonData: true,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
Ext.Msg.alert("Success", 'yea');
},
failure : function(response) {
var respObj = Ext.JSON.decode(response.responseText);
Ext.Msg.alert("Error", respObj.status.statusMessage);
}
});

Sending POST request with Amplifyjs

I want to send this POST request by amplifyjs
amplify.request.define('createItem', 'ajax', {
url: baseApiUrl + '/create/?folderid={folderid}',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8'
});
after that, the execution will be something like this:
createItem = function (callbacks, folderid, itemdata) {
return amplify.request({
resourceId: 'createItem',
data : {
folderid: folderid,
data: itemdata
},
success: callbacks.success,
error: callbacks.error
});
};
"itemData" is already a JSON string. I keep getting the Bad Request status code.
If I change the API URL to:
baseApiUrl + '/create
And after that pass:
return amplify.request({
resourceId: 'createItem',
data :data,
success: callbacks.success,
error: callbacks.error
});
It works just fine, but I need to pass the Id as well. Maybe, I'm missing something here.
You need to combine folderid and itemdata into a single data object. When Amplify reads your data object it will extract the folderid property and place it in the URL of the request. Then it will POST the remaining properties of the data object.

Resources