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
Related
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',
})
...
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)
I am working on an app that sends a POST request to a web service. My POST request looks like this:
$.ajax({
type: 'POST', url: getEntityUrl(), cache: 'false',
contentType:'application/json',
headers: {
'api-key':'myKeyHere',
'Content-Type':'application/json'
},
data: {
firstName:'Jon',
lastName:'Smith'
},
success: function() { alert('good job'); },
error: function() { alert('oops'); }
});
When I execute this, I'm getting a 400 Bad Request. I watched the request in Fiddler. I noticed that the parameters I sent are being sent as "firstName=Jon&lastName=Smith". However, they need to be sent across as JSON like I have them defined in the data parameter. I confirmed this is the problem by modifying the request in the composer in Fiddler. What am I doing wrong?
Thanks
If you pass jQuery a plain object through the data parameter (as you do here) then it will encode the data as application/x-www-form-urlencoded.
Just setting the contentType is insufficient.
If you want to send JSON then you must encode it yourself. You can use JSON.stringify for that.
data: JSON.stringify({
firstName:'Jon',
lastName:'Smith'
}),
You need to stringify the data like following.
$.ajax({
type: 'POST',
url: getEntityUrl(),
contentType: 'application/json',
headers: {
'api-key': 'myKeyHere',
'Content-Type': 'application/json'
},
data: JSON.stringify({ firstName: 'Jon', lastName: 'Smith' }), //change here
success: function () { alert('good job'); },
error: function () { alert('oops'); }
});
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
});
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'}
});