【问题标题】:Error in calling POST api in react native by handling action in redux通过处理 redux 中的操作来调用 POST api 在本机反应中出错
【发布时间】:2019-02-03 14:56:35
【问题描述】:

我正在使用 POST api 调用获取一些数据,其中我有数据和标头的令牌值,但我得到了错误的响应,我检查了许多文档但无法找出错误,这里是代码:

export const shareUserProfileHandler = (sharedReceiverData) => {
    return dispatch => {
        let formData = new FormData();
        for (let key in sharedReceiverData) {
            formData.append(key, sharedReceiverData[key]);
        }
         let requestConfig = {
             method: 'POST',
             headers: {
                 'Accept': 'application/json',
                 'Content-Type': 'multipart/form-data',
                 'Authorization': 'Token 97a74c03004e7d6b0658b14ddb'
             },
             body: formData
         };

        fetch(`http://api.com`, requestConfig)
        .then(response => response.json())
        .then(response => {
            alert('share user card api worked')

        })
        .catch(error => {
            alert('api error ' + error)
        })
    }
};

以上是捕获错误并显示 - SyntaxError: JSON Parse error: Unrecognized token'

【问题讨论】:

  • 可能响应不是 JSON,而是一些错误页面。 < 可能是 HTML 文档的开始。在 DevTools 的 Network 选项卡中检查状态代码/内容。

标签: javascript json react-native react-redux multipartform-data


【解决方案1】:

您的响应似乎不是 JSON。

替换

.then((response) => response.json())

对于

.then((response) => { console.log('response', response); response.json() })

并检查错误前的响应有什么问题。

【讨论】:

  • 我在其他项目中做了同样的事情,它成功运行,但这里显示错误....我现在替换为你的代码,它现在显示值 undefined
  • 如果响应未定义,则无法将其转换为 JSON。你能告诉 API 是什么吗?
  • 我将诸如 mobile_number 之类的输入参数作为表单数据提供,并以 json 格式获取响应输出为 { "id": 64, "rec_name": "", "mobile_number": "", "mobile_country_code" : "", }...
  • 我已经更新了我的代码看看,但错误仍然存​​在
  • 您能在 .json() 方法之前发布响应变量中的内容吗?
猜你喜欢
  • 2018-09-20
  • 2019-11-30
  • 1970-01-01
  • 1970-01-01
  • 2018-09-25
  • 2018-11-05
  • 2017-05-23
  • 2020-02-19
  • 2020-12-02
相关资源
最近更新 更多