问题
I working on replace some native-code with react native. The expected POST request (implemented in AFNetworking) in Charles should be like this:
Code snippet:
NSError *err;
NSData *paramData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&err];
NSData *paramData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&err];
NSString *paramString = [[NSString alloc] initWithData:paramData encoding:NSUTF8StringEncoding];
NSDictionary *param = @{@"data":paramString};
AFHTTPRequestOperation *operation = [manager POST:URLString parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (successBlock) {
successBlock(responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DebugLog(@"%zd", operation.response.statusCode);
if (failureBlock) {
failureBlock(operation, error);
}
}];
But the request from Fetch API version is like this:
Code snippet:
export default async (url, param) => {
var result = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'text/html',
},
body: JSON.stringify({
'data': JSON.stringify(param)
})
})
.then(response => checkStatus(response))
.then(response => response.json())
.catch(e => { throw e; });
return result;
}
My question is how can I send a post in fetch exactly as in AFNetworking? This cost me a lot of time. Thx!!
updated: The main difference is the annoying slashes and their body data structure, native one is json (data: paramString), while js string.
回答1:
Finally, my colleague found a solution. Request body should be constructed in this way:
body: 'data=' + JSON.stringify(param)
来源:https://stackoverflow.com/questions/45139583/how-can-i-construct-a-post-request-body-in-react-native-not-with-a-stringified-j