Reputation: 195
I have a phonegap application that uses
$.ajax(
type: 'POST,
dataType:"json",
url: 'test.com'
data: { mail: '[email protected]' }
)
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: '[email protected]' }),
})
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 !
Upvotes: 0
Views: 176
Reputation: 2352
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: '[email protected]' }),
})
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: "[email protected]"
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: '[email protected]' }
contentType: "application/json",
)
Note the contentType
parameter which actually tells jQuery
how to format the body of the request
Upvotes: 2