Difference between jquery ajax post and axios post - javascript

I am writing a new application using Vue.js As part of this I need to get an API token from a 3rd party. The ajax call below is working, and returns the expected response data object, however the axios call fails validation and returns an error message "Username and password cannot be empty". Any idea what I am doing wrong and why the two calls are being treated differently?
<script>
$(function(){
$.ajax(
{
type: "POST",
url: "https://testapi.XXXXXXXX.com/auth",
data: {
username:'TestUser',
password: 'TestPwd'
},
success: function(res){
console.log("from jquery",res);
}
}
)
})
</script>
<script>
var app = new Vue({
el:"#vueapp",
data:{
api_key: null
},
methods:{
getNewKey(){
axios({
method: 'POST',
url:'https://testapi.XXXXXXXX.com/auth'
,headers:{
'Content-Type':'application/x-www-form-urlencoded'
}
,data:{
username:'TestUser',
password: 'TestPwd'
}
})
.then(response =>{
console.log("From Axios",response);
})
}
},
created(){
this.getNewKey();
}
})
</script>

From the axios documentation:
https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format
You need to JSON.stringify your object passed in data.
data: JSON.stringify({username:'TestUser', password: 'TestPwd'})

Related

How can I convert jQuery ajax to fetch?

This was my jQuery code before. Now I want to change it to fetch.
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
I have changed the code to this now but I am getting bad request 400 status code
document.querySelector('#keyword').addEventListener('keyup',()=>{
let data = {
action: 'data_fetch',
keyword: document.querySelector("#keyword").value
};
let url = "<?php echo admin_url('admin-ajax.php'); ?>";
fetch(url, {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.text())
.then((data) => {
document.querySelector("#datafetch").innerHTML = data;
})
.catch((error) => {
console.error('Error:', error);
});
})
Am I missing something? It is from WordPress if this helps somehow.
You forgot the pcat property in the data object
jQuery, by default, sends form encoded data, not JSON encoded data. Use a URLSearchParams object instead of a string of JSON and omit the content-type header (the browser will add the correct one for you).
In your jQuery code you defined data as
data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },
and in fetch you defined it as
let data = {
action: 'data_fetch',
keyword: document.querySelector("#keyword").value
};
so, you are not passing some value which was previously passed. No wonder that your server errors out. Let's change your code to
let data = {
action: 'data_fetch',
keyword: document.querySelector("#keyword").value,
pcat: document.getElementById("cat").value
};
and try this out. If it still works, then you will need to find out what differs in the request and make sure that the request you are sending via fetch is equivalent to the request you formally sent via jQuery, then it should work well, assuming that the client-side worked previously with jQuery and the server-side properly handled the requests.

Using HTTP in NativeScript to send Post-data to a TYPO3-Webservice

I'm trying to send form data from a NativeScript app to a TYPO3-Webservice.
This is the JavaScript I'm using:
httpModule.request({
url: "https://my.domain.tld/webservice?action=login",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
username:username,
password:password
})
}).then((response) => {
console.log("got response");
console.log(response.content);
//result = response.content.toJSON();
callback(response.content.toJSON());
}, (e) => {
console.log("error");
console.log(e);
});
But I can't read this data in the controller. Even with this:
$rest_json = file_get_contents("php://input");
$postvars = json_decode($rest_json, true);
$postvars is empty. $_POST is empty, too (which is - according to some docs - because the data is sent as JSON and thus the $_POST-Array isn't populated.
Whatever I do, whatever I try, I can't get those variables into my controller.
I tried it with fetch as well as with formData instead of JSON.stringify, same result.
I might have to add, that when I add the PHP-part in the index.php of TYPO3, $postvars is being populated. So I guess something goes missing, until the controller is called.
Any ideas?
the nativescript part seems ok, your problem must be corrected in the server side.
i use similare call and its works
// send POST request
httpModule.request({
method: "POST",
url: appSettings.getString("SERVER") + '/product/list',
content: JSON.stringify(data),
headers: {"Content-Type": "application/json"},
timeout: 5000,
}).then(response => { // handle replay
const responseAsJson = response.content.toJSON();
console.log('dispatchAsync\n\tresponse:', responseAsJson);
}, reason => {
console.error(`[ERROR] httpModule, msg: ${reason.message}`);
});

export default new Vuex.Store and Mutations

I have problem with using commit like is described here. Probably problem is in that I use export default new Vuex.Store instead export const store = new Vuex.Store. But when I change this I have problem from this topic.
Here is my JS file, where I use Vuex and I want to call commit:
actions: {
signUserIn(payload) {
payload.password;
var params = new URLSearchParams();
params.append("grant_type", "password");
params.append("username", "admin");
params.append("password", "adminPassword");
axios({
method: "post",
url: "http://localhost:8090/oauth/token",
auth: { username: "my-trusted-client", password: "secret" },
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=utf-8"
},
data: params
}).then(function(response) {
const user = {
login: payload.username
};
localStorage.setItem("access_token", response.data.access_token);
this.commit("setUser", user);
});
}
},
Curently when I run this and I try call signUserIn I have this error in console: TypeError: Cannot read property 'commmit' of undefined
I don't have idea what can I type in google in this case.
I believe you have mistyped. It should be commit and not commmit.
EDIT: Seeing the file, please try using arrow functions instead.
axios({
method: "post",
url: "http://localhost:8090/oauth/token",
auth: { username: "my-trusted-client", password: "secret" },
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=utf-8"
},
data: params
}).then(response => {
const user = {
login: payload.username
};
localStorage.setItem("access_token", response.data.access_token);
this.commit("setUser", user);
});
This is because you will lose the context of this without it. With arrow functions, this remains the this from the outer context. Also, not sure if you need this in this particular case, but try with or without it. ( I said this too many times )
Note the signature of your action method is incorrect. The Vuex docs show that the action method takes the Vuex context (which contains the commit method) as the first parameter and the payload second:
// signUserIn(payload) { // DON'T DO THIS
signUserIn(context, payload) {
With your current code, you'll notice that payload.username and payload.password are undefined.
demo of your action with the bug
Your action method should look like this:
actions: {
signUserIn(context, payload) {
axios.post().then(response => {
context.commit('foo', foo);
});
}
}
demo of fix

Passing a query parameter from an AJAX get call to an express route

I'm playing around with a twitter API wrapper for Node right now and am trying to figure out how to pass a query parameter from an HTML form to an AJAX get request and have that parameter then passed into my Express route, rather than just having the form action go directly to the route.
Here's my HTML code
<form id="searchTerm">
Keyword:<input id="keyword" type="text" name="q" placeholder="Keyword">
<input type="submit">
</form>
My client-side Javascript
$(document).ready(function() {
$('#searchTerm').on('submit', function() {
$.ajax({
type: 'GET',
data: q,
url: '/search/tweets/term',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
And then my Node.JS route:
// Search by keywords or phrases
app.get('/search/tweets/term', function(req, res) {
var q = req.query.q;
// Accesses the Twitter API and pulls back the respective tweets
client.get('search/tweets', {q: q, count: 100, lang: 'en', exclude: 'retweets'}, function(error, tweets, response) {
if(!error) {
res.send(tweets);
} else {
console.log(error);
res.status(500).send(error.stack);
}
});
});
I'm getting a "Query Missing Parameters" error message in my terminal whenever I input a value into the form, however. Not sure what I'm doing wrong.
UPDATE
Got it working via the following:
$(document).ready(function() {
$('#searchTerm').on('submit', function(e) {
e.preventDefault();
var q = $('#keyword').val();
$.ajax({
type: 'GET',
data: {q: q},
url: '/search/tweets/term',
success: function(data) {
console.log(data);
}
})
})
})
However, since I'm implementing e.preventDefault(), I'm losing the query parameters within my URL. Since I want to give users the ability to share URL's to specific keywords, is there any way to be able to keep these parameters intact in the URL while still getting the JSON sent client side? Or will have to just manipulate the JSON on the server side and have the data be rendered in via a template engine?
Try this
$(document).ready(function() {
$('#searchTerm').on('submit', function() {
$.ajax({
type: 'GET',
data: q,
url: '/search/tweets/term?q=',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});

HttpClient PostAsync equivalent in JQuery with FormURLEncodedContent instead of JSON

I wrote a JQuery script to do a user login POST (tried to do what I have done with C# in the additional information section, see below).
After firing a POST with the JQuery code from my html page, I found the following problems:
1 - I debugged into the server side code, and I know that the POST is received by the server (in ValidateClientAuthentication() function, but not in GrantResourceOwnerCredentials() function).
2 - Also, on the server side, I could not find any sign of the username and password, that should have been posted with postdata. Whereas, with the user-side C# code, when I debugged into the server-side C# code, I could see those values in the context variable. I think, this is the whole source of problems.
3 - The JQuery code calls function getFail().
? - I would like to know, what is this JQuery code doing differently than the C# user side code below, and how do I fix it, so they do the same job?
(My guess: is that JSON.stringify and FormURLEncodedContent do something different)
JQuery/Javascript code:
function logIn() {
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
success: getSuccess,
error: getFail
});
} catch (e) {
alert('Error in logIn');
alert(e);
}
function getSuccess(data, textStatus, jqXHR) {
alert('getSuccess in logIn');
alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
alert('getFail in logIn');
alert(jqXHR.status); // prints 0
alert(textStatus); // prints error
alert(errorThrown); // prints empty
};
};
Server-side handling POST (C#):
public override async Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
// after this line, GrantResourceOwnerCredentials should be called, but it is not.
await Task.FromResult(context.Validated());
}
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
var manager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await manager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError(
"invalid_grant", "The user name or password is incorrect.");
context.Rejected();
return;
}
// Add claims associated with this user to the ClaimsIdentity object:
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
foreach (var userClaim in user.Claims)
{
identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
}
context.Validated(identity);
}
Additional information: In a C# client-side test application for my C# Owin web server, I have the following code to do the POST (works correctly):
User-side POST (C#):
//...
HttpResponseMessage response;
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password"),
new KeyValuePair<string, string>( "username", userName ),
new KeyValuePair<string, string> ( "password", password )
};
var content = new FormUrlEncodedContent(pairs);
using (var client = new HttpClient())
{
var tokenEndpoint = new Uri(new Uri(_hostUri), "Token"); //_hostUri = http://localhost:8080/Token
response = await client.PostAsync(tokenEndpoint, content);
}
//...
Unfortunately, dataType controls what jQuery expects the returned data to be, not what data is. To set the content type of the request data (data), you use contentType: "json" instead. (More in the documentation.)
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
contentType: "json", // <=== Added
success: getSuccess,
error: getFail
});
If you weren't trying to send JSON, but instead wanted to send the usual URI-encoded form data, you wouldn't use JSON.stringify at all and would just give the object to jQuery's ajax directly; jQuery will then create the URI-encoded form.
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: {
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
},
dataType: "json",
success: getSuccess,
error: getFail
});
// ...
To add to T.J.'s answer just a bit, another reason that sending JSON to the /token endpoint didn't work is simply that it does not support JSON.
Even if you set $.ajax's contentType option to application/json, like you would to send JSON data to MVC or Web API, /token won't accept that payload. It only supports form URLencoded pairs (e.g. username=dave&password=hunter2). $.ajax does that encoding for you automatically if you pass an object to its data option, like your postdata variable if it hadn't been JSON stringified.
Also, you must remember to include the grant_type=password parameter along with your request (as your PostAsync() code does). The /token endpoint will respond with an "invalid grant type" error otherwise, even if the username and password are actually correct.
You should use jquery's $.param to urlencode the data when sending the form data . AngularJs' $http method currently does not do this.
Like
var loginData = {
grant_type: 'password',
username: $scope.loginForm.email,
password: $scope.loginForm.password
};
$auth.submitLogin($.param(loginData))
.then(function (resp) {
alert("Login Success"); // handle success response
})
.catch(function (resp) {
alert("Login Failed"); // handle error response
});
Since angularjs 1.4 this is pretty trivial with the $httpParamSerializerJQLike:
.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
method: 'POST',
url: baseUrl,
data: $httpParamSerializerJQLike({
"user":{
"email":"wahxxx#gmail.com",
"password":"123456"
}
}),
headers:
'Content-Type': 'application/x-www-form-urlencoded'
})
})

Categories