【问题标题】:Retrieve body data node express检索正文数据节点快递
【发布时间】:2020-11-05 10:37:26
【问题描述】:

我正在尝试检索正文数据,但我只在我的终端上收到 undefined,不知道如何/在哪里检索“电子邮件”。 google了一下,没找到答案。

这是 app.js 文件:

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

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

//routes which should handle request

app.post("/orders", (req, res, next) =>{
    console.log(req.body.email);
    res.json(["Orange", "Apple", "Banana"]); 
});

//export app

module.exports = app;

这是 server.js 文件:

const http = require('http');

//import app.js file

const app = require('./app');

//define port to be used
const port = process.env.PORT || 3100;
const server = http.createServer(app);

server.listen(port, () =>{
    //print a message when the server runs successfully
    console.log("Success connecting to server!");
});

我想接收“名称”数据并在函数中使用它来返回一个 json。我正在使用邮递员仅用一个名为“电子邮件”的键发送帖子请求。不过,Postman 会收到我编写的 Json 测试数据“Orange, Apple, Banana”。

【问题讨论】:

    标签: node.js json api express body-parser


    【解决方案1】:

    对于x-www-form-urlencoded,您的示例应该可以正常工作(只需在 body 选项卡下的 Postman 中选择它)。

    如果您想以multipart/form-data 发布数据(例如文件),您可以安装multer middleware 并在您的应用程序中使用它:app.use(multer().array())

    // File: app.js
    const express = require('express');
    const bodyParser = require('body-parser');
    const multer = require('multer');
    
    const app = express();
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(multer().array());
    
    //routes which should handle request
    
    app.post("/orders", async (req, res, next) =>{
        console.log(req.body.email);
        res.json(["Orange", "Apple", "Banana"]);
    });
    
    //export app
    
    module.exports = app;
    

    这适用于:

    curl --location --request POST 'localhost:3100/orders' \
        --form 'email=john@example.com'
    

    curl --location --request POST 'localhost:3100/orders' \
        --header 'Content-Type: application/x-www-form-urlencoded' \
        --data-urlencode 'email=john@example.com'
    

    【讨论】:

    • 我试过邮递员(urlencoded)和curl,都有效,tks!但最后一个问题:一个简单的网络帖子表单也可以这样工作吗?
    • 取决于您的表格。如果您使用<form method="post">,它是x-www-form-urlencoded,但如果您使用<form action="post" enctype="multipart/form-data">,它将使用multipart/form-data 并允许文件上传。请参阅stackoverflow.com/a/4526286/982002 了解更多信息。
    猜你喜欢
    • 2018-12-15
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    相关资源
    最近更新 更多