ERPNext Foundation ERPNext Cloud User Manual Blog Discuss Frappé* Donate

How to call Login API using AJAX?


#1

Hi, I’m new to frappe framework. I would like to ask how to do simple call of the API using AJAX. Let say Login API. Here my code:

$.ajax({
type: ‘GET’,
url: ‘{mydomain}/api/method/login’,
data: {
usr: “Administrator”,
pwd: “admin”
},
success: function (data, status, xhr) {
console.log(data);
console.log(status);
console.log(xhr);
},
error: function (xhr, status, error) {
alert(“error”);
console.log(xhr);
console.log(status);
console.log(error);
}
});

This call result me:

“data” parameter always return nothing.
I tried to call via POSTMAN, it return me proper result.


#2

you might try using the postman ‘code’ function to prototype the JavaScript jquery AJAX code

I always used POST for login vs GET
Here’s an example of the output of selecting ‘code’ from Postman
Maybe’ll it’ll help. I hope so - otherwise Ajax is not my knowledge area - but I thought I’d put my 2 cents in anyway.

var settings = {
“async”: true,
“crossDomain”: true,
“url”: “http://ubuntu1604instance-erpnext/api/method/login”,
“method”: “POST”,
“headers”: {
“Content-Type”: “application/json”,
“Accept”: “application/json”,
“cache-control”: “no-cache”,
“Postman-Token”: “3ebe62f4-a9e2-484f-89b1-6e69a146243f”
},
“processData”: false,
“data”: “{“usr”:“Administrator”,“pwd”:“admin”}”
}

$.ajax(settings).done(function (response) {
console.log(response);
});

Also, the product (or byproduct) of the /api/method/login call is ultimately a cookie on the machine that made the login call - subsequent calls to the API look for that cookie and succeed if the cookie is found.
Does a call to /api/resource/Sales%20Order (for example) succeed after the above call to /api/method/login?

The other way to do this is by setting up OAuth, calling /api/method/frappe.integrations.oauth2.get_token to retrieve a Bearer key, and passing that key into a ‘Authorization’ header for calls to the API


#3

Hi mattlongfield,
Thanks for your reply.

Can you help me how I get this “Postman-Token” thing?


#4

Postman adds that automatically.
Just delete it, it’s not necessary to use in your code.