如何在 NodeJS 中允许表单数据

Haf*_*uri 3 api node.js postman

我最近创建了一个接受文件的 API。我正在尝试使用 Postman 测试 API。如果我使用x-wwww-form-urlencodedbody 类型发出 post 请求,一切正常,我会得到所有预期的数据。唯一的问题是它不允许发送文件。如果我使用form-data允许您发送文件的正文类型,我在后端不会收到任何内容。不确定 Postman 是否有问题,或者我做错了什么。我的预感是后端不接受form-data,这就是为什么我没有收到任何数据。我能做些什么来改变它?

到目前为止,我的标题看起来像这样,

res.setHeader('Access-Control-Allow-Origin', origin);
res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, form-data");
Run Code Online (Sandbox Code Playgroud)

应用程序.js

app
    // static route will go to the client (angular app)
    .use(express.static('client'))

    // secured routes
    .use('/api', secured_route)

    // add a user route
    .post('/user', user_api_controller.add_user)

    // delete this in the production
    .use(function(req, res, next) {
        res = allowed_orgins(req, res);
        next();
    })
;

allowed_orgins = function (req, res){
    var allowedOrigins = ['http://localhost:4200', 'http://localhost:8100'];
    var origin = req.headers.origin;
    if(allowedOrigins.indexOf(origin) > -1){
        res.setHeader('Access-Control-Allow-Origin', origin);
        res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, multipart/form-data");
    }
    return res;
}
Run Code Online (Sandbox Code Playgroud)

user_api_controller.js

module.exports.add_user = function (req, res) {
    console.log(req.body.username);
    console.log(req.body.other_parameters);
}
Run Code Online (Sandbox Code Playgroud)

如果我使用form-data,我不会在控制台上打印任何内容,但是当我使用x-wwww-form-urlencoded.


我已经用了multer middle ware,我仍然没有得到任何东西。当我的后端收到一些东西时,中间件就开始发挥作用了。我曾尝试获取 的纯文本字段form-data,但我也没有得到。这意味着我的后端无法接收所有form-data字段,不仅是文件,还包括文本字段。

Vla*_*pak 6

这是我的超级简单快递示例:

const express = require('express')
const fileUpload = require('express-fileupload');

const app = express()
app.use(fileUpload());

app.post('/file-upload', function(req, res, next) {
  console.log(req.body.msg);
  console.log(req.files);
  res.send('ok');
  next();
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})
Run Code Online (Sandbox Code Playgroud)

对不起,我不使用邮递员,但我使用curl它,它对我有用:

curl http://localhost:3000/file-upload \
  -H "Content-Type: multipart/form-data" \
  -F "file=@/YourDir/YourFile.txt" \
  -F "msg=MyFile"
Run Code Online (Sandbox Code Playgroud)

因此,您可以尝试、测试、获取要点并使用此 curl 命令玩您的应用程序。