添加正文时在 POST 请求中反应本机网络错误

Posted

技术标签:

【中文标题】添加正文时在 POST 请求中反应本机网络错误【英文标题】:React Native network error in POST request when adding a body 【发布时间】:2020-03-05 08:59:27 【问题描述】:

又是我。

我正在学习本机反应,现在我正在尝试上传文件,该 api 已经使用邮递员进行了测试并且它确实有效,所以我编写了以下代码:

import * as DocumentPicker from 'expo-document-picker';

async login () 
    let response = await DocumentPicker.getDocumentAsync(type: '*/*')

    const data = new FormData();
    data.append('file', response)

    // Fetch attempt ----------------------------------------
    fetch("http://192.168.0.3:8000/api/file", 
      method: "POST",
      headers:  
        "Content-Type": "application/x-www-form-urlencoded",
      ,
      body: data
    )
    .then(response => response.json())
    .then(response => 
      console.log("upload succes", response);
    )
    .catch(error => 
      console.log("upload error", error, JSON.stringify(error));
    );

    // Axios attempt ----------------------------------------
    axios.post('http://192.168.0.3:8000/api/file', data,  headers: "Content-Type": "application/x-www-form-urlencoded"  )
    .then(res => 
      console.log("goddaamittt wooork", res)
    )
    .catch(error => 
      console.log("error", error, JSON.stringify(error))
    );
  

当我从该请求中删除正文和标头时,它实际上返回了当您尝试在没有“文件”的情况下向其发布时 api 应返回的内容,一些消息“'fileName': 'A file is required'”但是将其添加到其中会出现网络错误,使用 fetch it 时出现的错误:

upload error [TypeError: Network request failed] "line":24646,"column":31,"sourceURL":"http://127.0.0.1:19001/node_modules/expo/AppEntry.bundle?platform=android&dev=true&minify=false&hot=false"

当它到达 axios 尝试时,它会这样说:

[Unhandled promise rejection: TypeError: Network request failed]

我尝试了我所知道的一切,我需要一些帮助!

Idk 如果它很重要,但这是 DocumentPicker 在我选择文件时返回的内容:

Object 
  "name": "FB_IMG_1573232116651.jpg",
  "size": 32482,
  "type": "success",
  "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fjsonplaceholder-bcb4c1c6-b37d-4634-99a5-3410d9b8654e/DocumentPicker/db8d78dd-2587-40e4-aed9-656c36df29f4.jpg",

这是我从 axios 请求中删除正文时遇到的错误

错误 [错误:请求失败,状态码 400] "config":"transformRequest":,"transformResponse":,"headers":"Accept":"application/json, text/普通,/","timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"方法":"post","url":"http://192.168.0.3:8000/api/file","response":"data":"message":"需要文件","status":400,"headers":" map":"cache-control":"public, max-age=0","x-robots-tag":"noindex","x-debug-token-link":"http://192.168.0.3:8000/_profiler/54e68c","x -debug-token":"54e68c","link":"http://192.168.0.3:8000/api/docs.jsonld; rel=\"http://www.w3.org/ns/hydra/core#apiDocumentation\"","content-type":"application/json","x-powered-by": "php/7.2.4","connection":"close","date":"Fri, 08 Nov 2019 17:54:12 GMT","host":"192.168.0.3:8000","config ":"transformRequest":,"transformResponse":,"headers":"Accept":"application/json, text/plain, /","timeout": 0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"method":"post","url":"http://192.168.0.3:8000/api/file", "请求":"url":"http://192.168.0.3:8000/api/file","凭据":"om it","headers":"map":"accept":"application/json, text/plain, /","method":"POST","mode": null,"referrer":null,"_bodyText":"","line":178773,"column":26,"sourceURL":"http://127.0.0.1:19001/node_modules/expo/AppEntry.bundle?platform=android&dev=true&minify=false&hot=false"

【问题讨论】:

【参考方案1】:

你应该尝试将内容类型修改为

fetch("http://192.168.0.3:8000/api/file", 
      method: "POST",
      headers:  
        'Content-Type': 'multipart/form-data',
      ,
      body: data
    )

对于 form-url-urlencoded,不支持获取。你得自己推。你可以看到这个answer。

【讨论】:

我一直收到同样的错误,当删除标题和正文时它实际上会执行请求,当我添加它们时它总是失败,无论如何:c【参考方案2】:

这是一个转储解决方案,我花了几个小时才找到这个:

当我从 DocumentPicker 获取文件时,我必须添加文件的类型,因为 DocumentPicker 返回一个名为“success”的奇怪类型,当我将其更改为“image/jpeg”时它起作用了:D 它根本不是解决方案因为我需要找到一种方法来知道用户选择的每个文件是什么类型的文件,无论如何,这段代码可以工作:

let response = await DocumentPicker.getDocumentAsync(type: 'image/jpeg')
    response.type = 'image/jpeg' // <- lasdfkasdfaslfkfsdkdsaf

    const data = new FormData();
    data.append('file', response);

    axios.post('http://192.168.0.3:8000/api/file', data , headers:  'Content-type': 'application/x-www-form-urlencoded'  )
    .then(res => 
      console.log("gooosh", res.data)
    )
    .catch(error => 
      console.log("error", error, JSON.stringify(error))
    );

【讨论】:

类型表示选择是否成功,不是文件类型 H3lltronik : 您如何确定 DocumentPicker 的 MIME 类型?

以上是关于添加正文时在 POST 请求中反应本机网络错误的主要内容,如果未能解决你的问题,请参考以下文章

向 API 请求 formData,上传图片时在 axios 中出现“网络错误”

网络请求失败对 https 图像上传 Android 做出本机反应

AJAX Post 请求错误:“不能为空”,[验证::required] 在 POST 正文中发送 JSON 对象时

axios 的网络错误和本机反应

尝试登录时反应本机,Firebase网络错误

在 Django 中使用 Axios 和 CORS 获取 POST 请求的错误请求并做出反应