簡體   English   中英

添加正文時在 POST 請求中反應本機網絡錯誤

[英]React Native network error in POST request when adding a body

又是我。

我正在學習本機反應,現在我正在嘗試上傳文件,api 已經使用 postman 進行了測試,它確實有效,所以我寫了這個代碼:

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 它時得到的錯誤:

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/plain, / "},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"method":"post","url": " http://192.168.0.3:8000/api/file "},"response":{"data":{"message":"File is required"},"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=\" Z80791B://www3AE7002FACB88C246876D .w3.org/ns/hydra/core#apiDocumentation \"","content-type":"application/json","x-powered-by":"PHP/7.2.4","connection":"close ","date":"2019 年 11 月 8 日星期五 17:54:12 GMT","host":"192.168.0.3:8000"}},"config":{"transformRequest":{},"transformResponse": {},"標題":{"A ccept":"application/json, text/plain, / "},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1 ,"方法":"發布","url":" http://192.168.0.3:8000/api/file "},"request":{"url":" http://192.168.0.3:8000 api/file ","credentials":"omit","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 "}

這是一個轉儲解決方案,我花了幾個小時才找到這個:

當我從 DocumentPicker 獲取文件時,我必須添加文件的類型,因為 DocumentPicker 返回一個名為“success”的奇怪類型,當我將其更改為“image/jpeg”時它起作用了:D 它根本不是一個解決方案,因為我會需要找到一種方法來知道用戶選擇的每個文件是什么類型的文件,無論如何,此代碼有效 c:

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

您應該嘗試將內容類型修改為

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

對於 form-url-urlencoded,不支持獲取。 你必須自己推它。你可以看到這個答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM