AJAX call POST Method - web-services

I am trying to call my web services using AJAX CALL. But i am getting with Unsupported Media Type Error in my firebug tool.
But it works fine in Rest-client Jar. Below is my code.
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:8888/taxi/add/driver", // Location of the service
data: {"firstName":"ttt","lastName":"gggg","gender":null}, //Data sent to server
//contentType: "application/json", // content type sent to server
//dataType: "json", //Expected data format from server
//processdata: true, //True or False
success: function (json) {//On Successfull service call
//shell.loaded();
alert("cross domain ajax success full.");
var result = json.firstName;
//alert("result===" + json.length);
//alert("result===" + json.data.length);
alert("result===" + result);
$("#dvAjax").html(result);
},
error: ServiceFailed// When Service call fails
});
return false;
});
});
function ServiceFailed(xhr) {
alert(xhr.responseText);
//if (xhr.responseText) {
// var err = xhr.responseText;
//if (err)
// error(err);
//else
error({ Message: "Unknown server error." })
//}
return;
}
please point out where is the mistake i have done. Thanks in Advance.
Regards
Karthick

What error you are getting? where does the response comes?? does it goes to success or error you should have specified dataType:'json'

Related

Expecting to get "non_field_errors: Unable to log in with provided credentials", but not getting it

Expectation: when wrong login credentials are provided, "non_field_errors: Unable to log in with provided credentials" is returned, such as below (screenshot from a tutorial which I'm following verbatim)
Reality: instead I'm getting the error below.
This gets printed to the console:
POST http://127.0.0.1:8000/api/v1/token/login 400 (Bad Request)
Interestingly I get this same error when I try to create users with passwords that are too short. I'm not having any issues with axios or the server when I provide the right credentials for log in, or use passwords of sufficient length when creating new users. When trying to catch errors such as these that I'm failing to get the expected result.
My code for catching the error is the same as in the tutorial:
methods: {
submitForm() {
axios.defaults.headers.common['Authorization'] = ''
localStorage.removeItem('token')
const formData = {
username: this.username,
password: this.password
}
axios
.post('/api/v1/token/login', formData)
.then(response => {
const token = response.data.auth_token
this.$store.commit('setToken', token)
axios.defaults.headers.common['Authorization'] = 'Token ' + token
localStorage.setItem('token', token)
this.$router.push('/dashboard/my-account')
})
.catch(error => {
if (error.response) {
for (const property in error.response) {
this.errors.push(`${property}: ${error.response.data[property]}`)
}
} else if (error.message) {
this.errors.push('Something went wrong. Please try again!')
}
})
}
}
Is there something in the server settings that I should change?
I'm using Django, rest framework, and djoser.
Don't know if you're using a custom exception handler in Django rest framework but it looks like the issue could be from the way you're handling the error in your frontend application.
You can handle the errors like this.
methods: {
submitForm() {
axios.defaults.headers.common['Authorization'] = ''
localStorage.removeItem('token')
const formData = {
username: this.username,
password: this.password
}
axios
.post('/api/v1/token/login', formData)
.then(response => {
const token = response.data.auth_token
this.$store.commit('setToken', token)
axios.defaults.headers.common['Authorization'] = 'Token ' + token
localStorage.setItem('token', token)
this.$router.push('/dashboard/my-account')
})
.catch(error => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
})
}
Can be found here

Rest-API call fails in lambda function

I'm new about lambda functions in AWS and I need some suggestions to figure out the nature of the problem.
AWS Lambda function based on Javascript using node.js 12.x.
I did set up local development environment based on SAM (sam cli/aws cli/docker/IntelliJ) on Ubuntu 18.04 and MacOs Catalina and a simple basic lambda function work, on both systems.
I can set up logs and see them on via IntelliJ when docker runs.
The function was created using sam init command from a terminal and selecting a simple hello world.
I did add a Rest-API call in it.
Nothing fancy, using request 2.88.2 (I know is deprecated and I did try to use other ways, all of them fails anyway so I'm stick with request for now).
Basically what is happening is that the call to the API "seems" not happening at all.
Logs placed before and after the API call are showing up.
Logs inside the API call, like to show the errors or results, are never showing up.
So far only in one case I was able to see an error message coming from the API, when I removed the URI.
And as expected the API returned an error message saying : invalid URI.
Otherwise NOTHING. Here some code.
This function is called from the lambda handler.
function getToken() {
const request = require('request');
const qs = require('querystring');
console.log("getToken function called");
let bodyData = qs.stringify({
username: 'test',
password: 'xxxxx',
grant_type: 'password'
});
console.log("getToken bodyData : " + bodyData);
let options = {
url: "https://blahblahblah/function",
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
},
form: bodyData
};
console.log("getToken options : " + options);
var request1 = request(options, function(err, response, body) {
console.log("returned from API call");
if (err) {
console.log("Error from getToken : " + err);
return null;
} else {
console.log("Answer from getToken : " + body);
return body;
}
});
}
I did test the connection and API using Postman and is working.
All the logs inside the request are NEVER coming up.
No matter changing options (did try many many different ways).
What am I doing wrong ?
Any suggestion on how to track this problem ?
Thanks
STeve
This is the correct behaviour. Because the function getToken is not waiting for the http request to complete. you should either convert the function to use promise/async-await or simply callback.
Promise
async function getToken() {
...
return new Promise((resolve, reject) => {
request(options, function (err, response, body) {
console.log("returned from API call");
if (err) {
console.log("Error from getToken : " + err);
resolve(null);
} else {
console.log("Answer from getToken : " + body);
resolve(body);
}
});
});
}
// Then in the lambda Handler:
// await getToken()
Callback
function getToken(callback) {
...
request(options, function (err, response, body) {
console.log("returned from API call");
if (err) {
console.log("Error from getToken : " + err);
callback(null);
} else {
console.log("Answer from getToken : " + body);
callback(body);
}
});
}
// Then in the lambda
getToken(() => {
// handle the http request response
})

Postman: how to send asynchronous request by script

I got two requests: A and B in postman. I want to send the request A first then send the request B while request A is still waiting for the response. It's quite easy to do this mannually because request A take 15s to finish.
But are there anyway I can do this automatically, because I am going to test this case a lot.
I have tried to use runner in postman but it always wait for request A to be finish before sending request B.
After that I found a document about sending asynchronous request in postman here.
I wrote a script that use pm.sendRequest to send request B and put that script in the pre-request of request A.
let confirmRequest = {
url: url + "/confirm",
method: "POST",
body: {
"requestId": (new Date()).getTime(),
"statusCode": "0",
}
}
setTimeout(function() {
pm.sendRequest(confirmRequest, function (err, res) {
console.log(err ? err : res.json());
});
}, 1500);
the problem is even I've wrapped it inside a setTimeout function, the request A still wait for pre-request to finish first. So in the end request B have been send before request A.
Are there any solution to this problem?
I tried but could not achieve asynchronously process requests using Postman or Newman. I found it easier to write a nodeJS code using async-await-promise concepts. Here is the sample code:
Sample Code that works for me:
var httpRequest "your raw request body";
var headersOpt = {
"content-type": "application/json",
};
const promisifiedRequest = function(options) {
return new Promise((resolve,reject) => {
request(options, (error, response, body) => {
if (response) {
return resolve(response);
}
if (error) {
return reject(error);
}
});
});
};
var output;
async function MyRequest(httpRequest,j, fileName) {
var options = {
uri: "url",
method: "POST",
body: httpRequest,
json: true,
time: true,
headers: headersOpt
}
try {
console.log('request posted!');
let response = await promisifiedRequest(options);
console.log('response recieved!');
output = output + ',' +response.elapsedTime;
console.log(response.elapsedTime);
console.log(output);
//return response;
} catch (err) {
console.log(err);
}
finally
{
//this code is optional and it used to save the response time for each request.
try{
fileName = (j+1)+'_'+fileName;
fs.writeFile('/logs-async/scripts/output/'+fileName+'.csv', output, (err) => {
//throws an error, you could also catch it here
if (err) throw err;
});
}
catch (err){
console.log(err);
}
}
}

Issue to hit webservice in sencha

I am trying to call registration webservive in sencha.When I call it on browser its seems ok.But i calling with in the app its gives following error.Please any body help me.
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
here is my code
Ext.Viewport.setMasked({xtype:'loadmask',message:'your custom loadmask'});
Ext.data.JsonP.request({
url: 'http://XXX.XXX.com/api/users/?',
params: {
first_name:'mohit',
last_name:'bisht' ,
city:'ramnagar',
state:'UK',
phone:'9073467465',
email:'test#test.com',
password_digest:'123456',
op:'s'
},
success : function(response,opts) {
Ext.Viewport.setMasked(false);
console.log(response.status);
},
failure : function(response,opts) {
Ext.Viewport.setMasked(false);
if (response.timedout) {
Ext.Msg.alert('error', 'Request to server timed out.');
}
else if (response.aborted) {
Ext.Msg.alert('error', 'Request Aborted by server.');
}
else {
Ext.Msg.alert('error', 'Invalid Request to server.');
}
}
});
Are you sure the service supports jsonp? you can try with an ajax request instead:
Ext.Viewport.setMasked({xtype:'loadmask',message:'your custom loadmask'});
Ext.Ajax.request({
useDefaultXhrHeader: false,
cors: true,
url: 'http://XXX.XXX.com/api/users/?',
params: {
first_name:'mohit',
last_name:'bisht' ,
city:'ramnagar',
state:'UK',
phone:'9073467465',
email:'test#test.com',
password_digest:'123456',
op:'s'
},
success : function(response,opts) {
Ext.Viewport.setMasked(false);
console.log(response.status);
},
failure : function(response,opts) {
Ext.Viewport.setMasked(false);
if (response.timedout) Ext.Msg.alert('error', 'Request to server timed out.');
else if (response.aborted) Ext.Msg.alert('error', 'Request Aborted by server.');
else Ext.Msg.alert('error', 'Invalid Request to server.');
}
});
Hope it helps-

getJSON callback not called when requesting a Facebook user

I am successfully authenticating a user to Facebook through my Spotify app, but then I try to request the user information and my .getJSON callback is never called. Here's my code :
auth.authenticateWithFacebook(facebookAppId, facebookPermissions, {
onSuccess: function(accessToken, ttl) {
var request_url = 'https://graph.facebook.com/me';
var url = request_url + '?access_token=' + accessToken;
$.getJSON(url, function(data) {
alert("Working");
});
},
onFailure: function(error) {
console.log("Authentication failed with error: " + error);
},
onComplete: function() { }
});
I tried with $.ajax, adding &callback=?, &callback=myFunction but nothing ever worked... Anyone have an idea of the issue?
Thanks
Make sure you add graph.facebook.com to the RequiredPermissions key in your manifest.json file.