node.js - 使用 node.js supertest 使用 multipart/form-data POST
问题描述
我试图使用 Node.js supertest 来测试一些 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 对象 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
真的没有任何类型的打字。通常,所有内容都将被解释为字符串。您的控制器将需要进行任何转换。
我可以使用变量代替硬编码的字符串吗?
是的你可以。
代替:
.field("userId", "5d921d306e96d70a28989127")
您可以使用:
.field("userId", userId)
只要你之前定义了一个 userId 变量
推荐阅读
- java - 尝试加载片段时出现 InflateException
- html - CSS - 堆叠元素在较小的屏幕上相互溢出
- python - 仅当另一列中的数据存在时,如何使用 Python 合并两列并覆盖一列中的数据?
- r - 如何在 R 的列表中找到最长的向量/列表?
- full-text-search - ObjectBox 是否支持全文搜索(fts)?
- javascript - Angular 2插值在谷歌地图的监听器内不起作用
- javascript - 在数据表表头中添加列名和选择框
- c# - MySQL:尝试读取结果集时遇到致命错误
- c++ - 如何访问双指针对象中的方法
- three.js - Panolens JS没有将点输出到控制台