NodeJS 如何从postman扩展“form-data”值中获取值

pbwdgjma  于 2022-11-22  发布在  Node.js
关注(0)|答案(4)|浏览(285)

我正在使用节点js与表达框架和休息api为休息api客户端我正在使用 Postman 扩展与chrome浏览器在这里我可以从选项“x-www-form-urlencoded”获得值,但我不能从“表单数据”获得值我想从“表单数据”选项获得值,还需要上传图像文件。请帮助我实现这一点。我想从“表单数据”获得值选项和图像。请帮助我。下面我提到的代码,我已经使用。x1c 0d1x

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var http = require('http').Server(app);
var mysql = require('mysql');
var util = require('util');
var trim = require('trim');
var validator = require('validator');
var bodyParser = require('body-parser');
var Ingest      = require('ingest');
var multer      = require('multer');
var upload = multer({ dest: 'uploads/' });
var type = upload.single('recfile');
 passport = require('passport')
 , LocalStrategy = require('passport-local').Strategy;

async = require('async');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ 
   extended: true 
}));

app.post('/upload', function(req, res){
    console.log(req.file); // "form-data" values not able to get here
    console.log(req);// "form-data" values not able to get here
    console.log('body : '+JSON.stringify(req.body));// "form-data"  values not able to get here
});

我没有在postman标题中设置任何内容类型

app.post('/upload', function(req, res){
    console.log('req.headers \n '+JSON.stringify(req.headers));     
    console.log('req.body.file :- '+req.body.file);
    console.log('\n\n req.body :- '+JSON.stringify(req.body));
});

我得到了上述代码的以下结果。req。头

{"host":"localhost:3001","connection":"keep-alive","content length":"5808","cache-control":"no-cache","origin":"chrome-extension://mkhojklkhkdaghjjfdnphfphiaiohkef","password":"password","user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36","username":"User2","content-type":"multipart/form-data; boundary=----WebKitFormBoundaryV4zAIbjEyKYxLRWe","accept":"*/*","accept-encoding":"gzip, deflate","accept-language":"en-US,en;q=0.8","cookie":"connect.sid=s%3Atz4f1ZgJkaAjuDD1sOkMB9rr.Z8EUIyxEcr0EyFQL96v0ExGRidM3SAVTx8IIr52O0OI"}

请求主体文件:-未定义
请求正文:- {}

kxkpmulp

kxkpmulp1#

是的,同样的问题我遇到了几次,根据我的经验,你不设置内容类型的 Postman 头,因为它应该是未定义的,节点服务器自动设置的内容类型根据需求。如果你设置的内容类型,那么你不会得到任何图像和其他数据在节点服务器。
1.从req.body.文件中获取图像
1.从req.body获取其他数据
1.在中间件中使用(multipart())
如何将multipart用作中间件的过程

  1. var multipart =需要('连接多方');
    1.(global.app。
    1.应用程序使用(multipart());
vs3odd8k

vs3odd8k2#

我得到了解决方案的帮助下的代码

var express = require('express');
    var router = express.Router();
    var util = require("util"); 
    var fs = require("fs");
    var formidable = require('formidable');
    var path = require('path');

    router.post("/upload", function(req, res, next){ 
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        // `file` is the name of the <input> field of type `file`
        console.log(files);
        console.log(fields);
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        res.end(util.inspect({fields: fields, files: files}));
    });
    form.on('error', function(err) {
        console.error(err);
    });
    form.on('progress', function(bytesReceived, bytesExpected) {
        var percent_complete = (bytesReceived / bytesExpected) * 100;
        console.log(percent_complete.toFixed(2));
    });
    form.on('end', function(fields, files) {
        /* Temporary location of our uploaded file */
        var temp_path = this.openedFiles[0].path;
        /* The file name of the uploaded file */
        var file_name = this.openedFiles[0].name;
        /* Location where we want to copy the uploaded file */
        var new_location = 'public/images/';

        fs.readFile(temp_path, function(err, data) {
            fs.writeFile(new_location + file_name, data, function(err) {
                fs.unlink(temp_path, function(err) {
                    if (err) {
                        console.error(err);
                        } else {
                        console.log("success!");
                    }
                });
            });
        });
    });
});
vdzxcuhz

vdzxcuhz3#

我认为您需要为此使用body-parser,还需要将您的app.js更新为

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));
yeotifhr

yeotifhr4#

我遇到了同样的问题,我不能得到表单数据字段的主体解析器是不够的,以获得这些值。点击谷歌搜索了很多东西,但没有工作。这里是我如何得到表单数据值的解决方案。
注意:我使用的是typescript而不是js
1.安装multer软件包:npm i multer
1.现在在app.tsapp.js相应地导入:

import multer from "multer"

1.定义multer函数

const upload = multer(); // config

1.正文解析器之后:

app.use(upload.any());

相关问题