How can I construct a POST request body in React Native not with a stringified json but a json?

孤者浪人 提交于 2019-12-11 00:34:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!