Jwqq Jwqq - 1 month ago 11
Javascript Question

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!

Answer

$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

Comments