簡體   English   中英

使用 node.js supertest 使用多部分/表單數據進行 POST

[英]POST with multipart/form-data using node.js supertest

我試圖使用 Node.js 超級測試來測試一些 REST API。

request(app)
      .post("/products")
      .set(
        "Authorization",
        "Bearer my jwt token here"
      )
      .set("Content-Type", "multipart/form-data")
      .field("name", "Tomato")
      .field("userId", "5d921d306e96d70a28989127")
      .attach(
        "productImage",
        "D:/NodeJS/node-rest-shop/uploads/1558612339690managing-redis.jpg"
      )
      .expect(201)
      .then(res => {
        const body = res.body;
        expect(body).to.contain.property("message");
        expect(body).to.contain.property("productId");
        expect(body).to.contain.property("date");
        expect(body).to.contain.property("user");
        expect(body).to.contain.property("request");
        done();
      })
      .catch(err => done(err));

.field("userId", userId )

有沒有辦法在不設置硬編碼字符串值的情況下將userId的值設置為變量? 它是 MongoDB object id。

當我使用 value 作為變量時,發生了此錯誤。

TypeError: source.on is not a function
    at Function.DelayedStream.create (node_modules\delayed-stream\lib\delayed_stream.js:33:10)
    at FormData.CombinedStream.append (node_modules\combined-stream\lib\combined_stream.js:45:37)
    at FormData.append (node_modules\form-data\lib\form_data.js:74:3)
    at Test.RequestBase.field (node_modules\superagent\lib\request-base.js:406:23)
    at Context.done (test\api\product\product.js:77:8)

我可以將其解釋為兩種不同的方式,所以我將同時回答:

可以將值指定為非字符串,例如數字。

multipart/form-data實際上沒有任何類型的類型。 通常,所有內容都將被解釋為字符串。 您的 controller 需要進行任何轉換。

我可以使用變量代替硬編碼的字符串嗎?

是的你可以。

代替:

.field("userId", "5d921d306e96d70a28989127")

您可以使用:

.field("userId", userId)

只要你之前定義了一個 userId 變量

userId 是一個new mongoose.Types.ObjectId() 因此,它不返回字符串,而是返回 object。 您需要將其轉換為字符串。 我們可以使用這個。 .field("userId", String(userId))

暫無
暫無

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

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