简体   繁体   English

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

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

I am trying to send input data from a form to my nodejs endpoint.我正在尝试将输入数据从表单发送到我的 nodejs 端点。 However, when I print the req.body, it returns undefined and I am not sure why.但是,当我打印 req.body 时,它返回 undefined,我不知道为什么。

Relevant API code:相关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);

I decided to use app.use instead of app.get because I want to eventually handle the body and place it into my ejs template and render it to display.我决定使用 app.use 而不是 app.get 因为我想最终处理正文并将其放入我的 ejs 模板中并渲染它以显示。 To my understanding, you cannot use a request body in a get request.据我了解,您不能在获取请求中使用请求正文。

Relevant client side form:相关客户端表格:

       <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>

console:安慰:

{}
undefined

any help will be greatly appreciated, I am a noobie when it comes to API development so it will mean the world to me to get a response back.任何帮助将不胜感激,当谈到 API 开发时,我是个菜鸟,所以这对我来说意味着世界得到回应。

Seems like 2 issues好像有2个问题

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

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

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

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

it will parse the incoming body.它将解析传入的正文。

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

Consider an example:考虑一个例子:

If I have a route name / and I want to render the data name index.jade or index.ejs or index.handlebars that I have specified in view engine then如果我有一个路由名称/并且我想呈现我在视图引擎中指定的数据名称 index.jade 或 index.ejs 或 index.handlebars 然后

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

if I want to pass some data in view while render then如果我想在渲染时传递一些数据

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

and In template considering it to be handlebars {{title}}并且在模板中认为它是车把{{title}}

Now app.post is used for recieving the data.现在app.post用于接收数据。 You cannot access req.body in GET method.您无法在GET方法中访问req.body Although you can access the query params in both GET and POST虽然您可以在GETPOST中访问查询参数

I think your form is not sending data as intended to the API endpoint.我认为您的表单未按预期向 API 端点发送数据。 That's why it is returning empty object.这就是为什么它返回空的 object。

You can check this.你可以检查一下。 Install postman if you don't have it and run:安装 postman 如果你没有它并运行:

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

Also, try to run this:另外,尝试运行这个:

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');
});

Also, I get request you can't access body as It is used to request data.另外,我收到您无法访问正文的请求,因为它用于请求数据。

By design, the POST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it.按照设计,POST 请求方法请求 web 服务器接受请求消息正文中包含的数据,很可能用于存储它。 It is often used when uploading a file or when submitting a completed web form.它通常在上传文件或提交完整的 web 表单时使用。 In contrast, the HTTP GET request method retrieves information from the server.相比之下,HTTP GET 请求方法从服务器检索信息。

In your form please add this:请在您的表格中添加以下内容:

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

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

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