Angularjs - equal sign in $http post data

2019-05-12 00:56发布

问题:

I'm using angularjs' $http service to post data to my API. It works great.. until I add and equals sign to the contents of data (JSONRequest in example)

var request = {
    'method': 'POST',
    'url': API_URL + apiActionName,
    'data': JSONRequest,
    'withCredentials': true,
};
$http(request).
success(function(data, status, headers, config) {
    // handle success
}).
error(function(data, status, headers, config) {
    // handle error
}

this works for data contain the following JSONRequest

{
    'text':'this is  some text'
}

however when the data contains this

{
    'text':'this is = some text'
}

the request is escaped and the server cannot do anything with the POST!! It seems to work with all other characters.

Any help would be greatly appreciated! Thanks

回答1:

I always use JSON.Stringify() for my POST payloads.



回答2:

It had to do with URI encoding. The string that was getting getting sent the the lower level AJAX API was not uri encoded. This means that when it saw the = sign in the post it was parsing it assuming uri encoding.

All of the information may not have been present to answer this question as JSONRequest was originally was defined on the line above var request. Sorry about that. It was defined as follows:

var JSONRequest = {
    'JSON': requestObject;
}

where requestObject was

{
    'text':'this is = some text'
}

I ended up URI encoding the JSON Request as follows

var JSONRequest = 'JSON=' + encodeURIComponent(JSON.stringify(requestObject));

This fixed the problem and made my API calls more robust to the HTTP protocol.

Thanks for all the help!!