Anti Forgery Token Axios Asp .Net Core - javascript

Hi i am able to send a post using vue js axios to a controller in Asp .NET Core 2.2 like this
axios({
url: '/Parametros/Create',
method: 'post',
ContentType: 'application/json',
data: formData
})
however for this to work i have to remove from my action in controller
[ValidateAntiForgeryToken]
Also the token is generated in razor pages as input
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8GwWLSmGzLVOqfs-yISjocyQshOjT98BeCqxo14sO91JGUZPe_IstyK9DWZyu0rCr0bxdx3lBlwminvxm7q0zXVWcUkAZIH8NwKDYGdNCiY-Z_BgMzLt_1PyNEHxfpmTouJgMu3il8N4fMjbI0ohwElXGK-eVLXGuzj_J5N_uQ3A4f-9ijmTKGk8p3BC7hrB1A">
I tried
axios({
url: '/Parametros/Create',
method: 'post',
headers: {
"__RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val();
}
ContentType: 'application/json',
data: formData
})
and
axios({
url: '/Parametros/Create',
method: 'post',
ContentType: 'application/json',
data: {
"__RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val(),
formData
}
})
None work, I keep getting bad request... Using ajax the 2nd approach works fine but axios not. How can i handle this?

Changing __RequestVerificationToken to RequestVerificationToken in the header made a post request work for me.
Final code:
axios({
method: 'post',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
url: 'home/axiostest',
})
...

Related

put request in angular sends empty form data

I am trying to make a put request.
The api requires an array of numbers as request parameter
$http({
'requestpath/putrequesturl',
{
categories: [categorylist]
},
{
'method': 'PUT',
'authToken': authToken,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
the data is sent as
requestpath/putrequesturl?categories=%5B5,19,12%5D
the query string parameter shows correct data, but Form Data in chrome dev tools is empty.
I tried this without content-type too, but it does not work
How can i make this request to send data as Form Data (Request body)
Edit: this is what api requires to get sent (if this is necessary):
Parameter: categories type:array
Your $http params looks a little odd. Maybe you are trying to do something like this..
$http({
method: "PUT",
uri: 'requestpath/putrequesturl',
headers: {
"Content-Type": "application/json",
"authToken": authToken // assuming this should be in the header
},
data: {
categories: [categorylist]
}
})
This is how the method put should seems
$http({
method: 'PUT',
url: uri,
headers: {"Content-Type": "application/json;charset=UTF-8"},
data: someData
});
or
$http.put(url, data, config)

AJAX POST request using JQuery with body and URL parameters

I'm learning how to make AJAX calls with JQuery and one thing I was wondering if it's possible to do is include some data as URL parameters and other data in the post body. For example, I'd like to do something like this:
$.ajax({
url: '/myURL',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
but in addition to the JSON data which is being sent in the POST request body, I'd like to include URL parameters. Is there a way to do this?
You would be able to include the variables in the url portion of your code. For example
var example1 = "some_information";
$.ajax({
url: '/myURL',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
would become
var example1 = "some_information";
$.ajax({
url: '/myURL?var1=example1',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
You may need to put quotes around the example1 variable to ensure it doesn't break when there are spaces in the url.
You can send parameters normally in the URL as in the get request
either using ? and &
$.ajax({
url: '/myURL?data2=' + data2 + '&data3=' + data3,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
or by set them between /
$.ajax({
url: '/myURL/' + data2 + '/' + data3,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
The way of including the parameters on the URL will depends of the way you receive/parse them on the server side, however this is not considered as good practice for the post request.

how to covert the jquery ajax reques to angular http request

I am trying to convert old javascript ajax call to angular by using $http method in Angular.
My old one is like
var payload ={'id':'id-abc'}
$.ajax({
type: 'post',
url: 'myurl/com',
dataType: 'json',
data: payload,
success: function (returndata) {
//parse returndata
});
});
in Angular way,
$http({
method: 'post',
url: ‘myurl/com’,
dataType: 'json',
data: payload
}).then(function(returndata) {
console.log(returndata);
})
The angular way gave me
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. Issue.
If I mimic the old way and setup the content-type header like
$http({
method: 'post',
url: ‘myurl/com’,
dataType: 'json',
data: payload,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(returndata) {
console.log(returndata);
})
The server response is saying I am missing a params (it doesn’t).
I don’t have the control on the server side so I am not sure how to covert the old $ajax request to the new Angular one. Any ideas? Thanks a lot!
$http default is to serialze data as json
To send form encoded you need to use $httpParamSerializerJQLike which also needs to be injected wherever you use it
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
You could also set up global defaults for the header and a $httpInterceptor to do this transform instead of putting in each individual request

Add mime Content-ID to request payload (AJAX)

I need to add "<message>" as a Content-ID to my ajax request for my multipart form. I have a pretty simple request using Backbone's save:
var data = new FormData();
data.append('message', new Blob([JSON.stringify(message.attributes)],{type: "application/json"}),'message');
data.append(document.getElementById('fileInput').files[0].name,document.getElementById('fileInput').files[0]);
message.save({},{
contentType: 'multipart/form-data',
data: data
});
The first part of the form, "message," should have a Content-ID header. Any idea on how to achieve this?
As Backbone.Model.save uses $.ajax to interact with server, you can set custom headers using $.ajax's options.
Using headers options:
message.save({},{
headers: {"Content-ID": "<message>" },
contentType: 'multipart/form-data',
data: data
});
Using beforeSend callback of $.ajax:
message.save({},{
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-ID", "<message>");
},
contentType: 'multipart/form-data',
data: data
});

AngularJS Http vs Jquery Ajax

i'm trying to send to a ws a post request using some parameters.
in Ajax i do:
$.post("http://myWS",{name:"xxx",surname:"yyy"},function(response){
console.log(response);
});
this generate that payload:
{name:"xx",surname:"yyy"}
In AngularJS i do:
return $http({
method: 'POST',
async : true,
cache : false,
url: "http://myWS",
data: {name:"xxx",surname:"yyy"},
});
And this generates that paylaod:
{"name":"xxx","surname":"yyy"}
As you can see this payload differs from ajax one.
I tried to add header to $http request:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
but results is the same.
what could be the problem??
thanks!
I solved setting headers and params in this way:
return $http({
method: 'POST',
async : true,
cache : false,
url: "http://myWS",
data: $.param({name:"xxx",surname:"yyy"}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

Categories

Resources