Passing from ajax to fetch on client side with a glassfish server - 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 tryed
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: 'mail=bob#test.com',
})
and i tryed
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ mail: 'bob#test.com' }),
})
but neither of these worked, i'm deseperately having request.getParameter('mail') == null on server side.How can i do ?Note : i don't want to change the way the server handles things.

Related

basic structure for converting ajax to axios?

Can some one give me example of how to convert ajax to axios ?
I am trying to convert this code into axios
$.ajax({
type: 'POST',
url: 'http://example.com/storeauthcode',
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
axios.post('http://example.com/storeauthcode', authResult['code'], {
headers: {
'X-Requested-With': 'XMLHttpRequest'
'Content-Type: 'application/octet-stream; charset=utf-8',
},
transformResponse: (data) => { // do something with your data },
});
However a better place for the content-type would be the axios instance config itself.
Configure once globally:
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Then per request:
const result = await axios.post(
'http://example.com/storeauthcode',
authResult['code'],
{
headers: {
'Content-type': 'application/octet-stream; charset=utf-8'
}
}
);

Laravel Authentication with Passport,how send token Bearer in ajax header inside laravel project

I can get response from RESTful api when using Postman with Authorization Bearer + token.
But How can I send request with token in ajax (i made it inside my laravel project).
$.ajax({
url: "url",
headers: {
'Authorization': authorizationToken,
},
type: "post",
data: data,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
},
error: function (data, status, error) {
}
});
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN":$('meta[name="csrf-token"]').attractive('content')
"Authorization":"Bearer"+localStorage.getItem('token')
}
});

React Native getting response 400 when post to oauth/token using laravel passport

I am trying to login through oauth/tokens from my React Native project. I have tested with POSTMAN When i send the data from axios it works well. But when i try to send from my app it gives me Error: Request failed with status code 400
my code is :
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
data: {
client_id : '2',
client_secret : 'secret',
grant_type : 'password',
email : this.state.userEmail,
password : this.state.userPassword
}
})
.then((response) => {
console.log(response.data);
})
I've solved the problem in this way:
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
data: 'client_id=2&client_secret=secret&grant_type=password&email=' + this.state.userEmail+'&password='+this.state.userPassword
})
.then((response) => {
console.log(response.data);
})
Seems Axios have some problem to process the data in json format.
If you use Webpack you must also configure the proxy.

Cannot pass authentication sending ajax request to mailgun

I can do this:
curl --user 'api:MYAPIKEY' -F from=foo#bar.it -F to=MYEMAIL#gmail.com -F subject='foo' -F text='bar' https://api.mailgun.net/v3/sandbox93d8299f673a4c3295b7592956cb3d9.mailgun.org/messages
but I get a login popup when I try to do the same request with jquery .ajax() method:
$.ajax({
headers: {"Authorization": "Basic api:key-b50a9065a7b9bdf464f3d7a418ca96bb"},
// url: "././mail/contact_me.php",
url: "https://api.mailgun.net/v3/sandbox93d8299f673a4c32952b7592956cb3d9.mailgun.org/messages",
type: "POST",
dataType: 'json',
data: {
name: name,
phone: phone,
email: email,
message: message
},
// cache: false,
success: function() {
alert('ok');
},
error: function() {
alert('problems');
}
}
The server respond with a 401. any idea why?
thank you
Try using the username and password fields
$.ajax({
url: "https://api.mailgun.net/v3/sandbox93d8299f673a4c32952b7592956cb3d9.mailgun.org/messages",
type: "POST",
dataType: 'json',
username:'api',
password: 'key-b50a9065a7b9bdf464f3d7a418ca96bb',
...
If you're setting the header yourself you have to base64 encode it
headers: {"Authorization": "Basic "+btoa("api:key-b50a9065a7b9bdf464f3d7a418ca96bb")},

Getting data from web service using ajax

I'm trying to get data from a webservice using ajax and POST method.
Ext.Ajax.request({
url: 'http://localhost......',
method:'POST',
success: function(response) { console.log(response.responseText); },
failure: function() { Ext.Msg.alert('Fail'); },
jsonData:{
/*Here I specify my request json*/
}
}
});
The above thing works fine but when i try to mimic the same in EXTJS store it responds with a error
he server responded with a status of 415 (Unsupported Media Type)
EXTJS STORE CODE
Ext.define('IWM.store.JsonTest', {
extend: 'Ext.data.Store',
autoLoad: true,
fields:['Name'],
proxy: {
type: 'ajax',
method : 'POST',
actionMethods: {
create : 'POST',
read : 'POST',
update : 'POST',
destroy: 'POST'
},
jsonData:{
/*JSON */
}
},
url: 'http://localhost......',
success: function(response) { console.log(response.responseText); },
failure:function(){console.log("failed");},
reader: {
type: 'json',
root: 'result',
successProperty: 'success'
}
}
});
First things first, try to change store config as below.
var IWMStore = new Ext.data.JsonStore({
// it seems to me you had forgotten model
model: 'YourDataModel',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'http://your-url-address',
reader: {
type: 'json',
root: 'json-root-value',
idProperty: 'unique-property-in-json-file'
}
}
});
Example JSON value :
// here, ctgMains is the root value, CUST_ASSORT_SECTION_ID is the idProperty
{"ctgMains":[{"CUST_ASSORT_SECTION_ID":"1","CTG_SECTION":"HORECA"},{"CUST_ASSORT_SECTION_ID":"7","CTG_SECTION":"SCO"},{"CUST_ASSORT_SECTION_ID":"3","CTG_SECTION":"TRADER"}]}
Second Attempt :
Try to add headers property in your proxy definition, like below:
proxy: {
type: 'ajax',
url: 'http://your-url-address',
reader: {
type: 'json',
root: 'json-root-value',
idProperty: 'unique-property-in-json-file'
},
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
}
}
Following on from Oğuz Çelikdemir's answer, you may need to define a json writer for your proxy.
proxy: {
type: 'ajax',
url: 'http://your-url-address',
reader: {
type: 'json',
root: 'json-root-value',
idProperty: 'unique-property-in-json-file'
},
writer: {
type: 'json'
}
}
That should set the json mediatype header (assuming that's what your request is expecting).

Resources