繁体   English   中英

NodeJS,HTML 表单,端点,req.body 返回未定义

[英]NodeJS, HTML Form, Endpoint, req.body returning undefined

我正在尝试将输入数据从表单发送到我的 nodejs 端点。 但是,当我打印 req.body 时,它返回 undefined,我不知道为什么。

相关API代码:

var bodyParser = require('body-parser')
var express = require('express');
var app = express();
var https = require('https');
var cors = require('cors');
var server = https.createServer({
    key: fs.readFileSync('../../ssl/keys/'),
    cert: fs.readFileSync('../../ssl/certs/'),
    requestCert: false,
    rejectUnauthorized: false
},app);


var io = require('socket.io')(server, {
    cors: 
    {
      origin: "http://127.0.0.1:5500",
      methods: ["GET", "POST"]
    }
  });
app.set('views','./views');
app.set('view engine', 'ejs');
app.use(express.static('public')); //where our javascript goes
app.use(express.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use(cors());
  
app.use('/', (req, res)  => {
    console.log(req.body);
    const {data} = req.body;
    console.log(data);
    res.render('index');
});

server.listen(3001);

我决定使用 app.use 而不是 app.get 因为我想最终处理正文并将其放入我的 ejs 模板中并渲染它以显示。 据我了解,您不能在获取请求中使用请求正文。

相关客户端表格:

       <form action="https://goldengates.club:3001" method="post">
            <div class="searchBox">

                <input class="searchInput"type="text" name="user" placeholder="explore" value="explore">
                <button type="submit" class="searchButton"> <!--WILL NEED TO FIX THIS FOR MOBILE!-->
                <img class="icon" src="img/search1.png" alt="Electricity" title="Electricity">
                </button>
            </div>
          </form>

安慰:

{}
undefined

任何帮助将不胜感激,当谈到 API 开发时,我是个菜鸟,所以这对我来说意味着世界得到回应。

好像有2个问题

app.use('/', (req, res) => {});

使用app.post('/', (req, res) => {});

app.use will channel every request as it is for binding middleware to your application.

其次添加body-parser模块作为中间件。 app.use(require('body-parser')) ;

它将解析传入的正文。

app.get is used for rendering the view engine and display the data in the page.

考虑一个例子:

如果我有一个路由名称/并且我想呈现我在视图引擎中指定的数据名称 index.jade 或 index.ejs 或 index.handlebars 然后

app.get("/", (req, res) => {
  return res.render(index);
})

如果我想在渲染时传递一些数据

app.get("/", (req, res) => {
      return res.render(index, {title: "Some Title"});
    })

并且在模板中认为它是车把{{title}}

现在app.post用于接收数据。 您无法在GET方法中访问req.body 虽然您可以在GETPOST中访问查询参数

我认为您的表单未按预期向 API 端点发送数据。 这就是为什么它返回空的 object。

你可以检查一下。 安装 postman 如果你没有它并运行:

http://localhost:3001?name="testname"

另外,尝试运行这个:

app.post('/', (req, res)  => {
    console.log(req); --> check on req object what all is coming 
    const {data} = req.body;
    console.log(data);
    res.render('index');
});

另外,我收到您无法访问正文的请求,因为它用于请求数据。

按照设计,POST 请求方法请求 web 服务器接受请求消息正文中包含的数据,很可能用于存储它。 它通常在上传文件或提交完整的 web 表单时使用。 相比之下,HTTP GET 请求方法从服务器检索信息。

请在您的表格中添加以下内容:

<form action="URL" method="post" enctype="multipart/form-data">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM