【问题标题】:How can I construct a POST request body in React Native not with a stringified json but a json?如何在 React Native 中构造 POST 请求正文而不是字符串化的 json 而是 json?
【发布时间】:2017-12-21 17:11:21
【问题描述】:

我正在用 react native 替换一些本地代码。 Charles 中的预期 POST 请求(在 AFNetworking 中实现)应该是这样的:

代码sn-p:

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);
    }
}];

但是Fetch API版本的请求是这样的:

代码sn-p:

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;
}

我的问题是如何在fetch 中发送与AFNetworking 完全相同的帖子?这花费了我很多时间。谢谢!!

更新:主要区别在于烦人的斜杠及其body数据结构,原生的是json(data:paramString),而js是字符串。

【问题讨论】:

  • 如果您想要返回 JSON 响应,是否有某些原因您要发送 Accept: text/html 请求标头?因为那是要求服务器向您发送 HTML 响应,对吗?不是 JSON……
  • 无需在body中对param进行字符串化
  • @Engineer,但是服务器 api 要求这个结构,正如你在我的 Objective-C 代码中看到的那样。
  • @sideshowbarker ,与请求无关,只定义响应数据。在text/html 中,在本机实现中效果很好。

标签: ios react-native post fetch-api


【解决方案1】:

最后,我的同事找到了解决办法。请求正文应该这样构造:

body: 'data=' + JSON.stringify(param)

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 2016-07-19
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多