簡體   English   中英

在節點JS表達請求中接收空對象

[英]Receive empty object in node js express request

當我將圖像從本機上傳到節點js服務器時出現問題,這是我的代碼

客戶

var url = "http://192.168.55.120:3000/uploadimg";
var file = this.state.imgsrc.uri;
const data = new FormData();
data.append('token', 'testName'); 
data.append('photo', {
  uri: file,
  type: 'image/jpeg', 
  name: 'testPhotoName'
});
fetch(url, {
  method: 'post',
  headers: {
    'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
    'Content-Type': 'multipart/form-data'
  },
  body: data
}).then(res => {
  console.log(res)
});

和我的服務器代碼

const   express         = require('express'),
        bodyParser      = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/uploadimg', function (req, res) {
    console.log(req.body); // =====> empty object       
})

我的代碼錯了嗎?

正如您可以在body-parser docs中檢查的那樣,此程序包不處理多部分表單數據主體。

由於其復雜且通常較大的性質,因此無法處理多部分實體。 對於多部分實體,您可能對以下模塊感興趣:

 busboy and connect-busboy multiparty and connect-multiparty formidable multer 

另外,您無需在fetch指定內容類型標頭; 它會根據所提供的主體為您處理。

您不能按照文檔中提到的形式對formData stringify處理

使用FormData API是最簡單,最快的方法,但是具有無法對收集的數據進行字符串化的缺點。

如果要對提交的數據進行字符串化,請使用pureAJAX方法。

您可以考慮使用util-inspect嘗試

暫無
暫無

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

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