简体   繁体   中英

NodeJS, HTML Form, Endpoint, req.body returning undefined

I am trying to send input data from a form to my nodejs endpoint. However, when I print the req.body, it returns undefined and I am not sure why.

Relevant API code:

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

Seems like 2 issues

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

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

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

Now app.post is used for recieving the data. You cannot access req.body in GET method. Although you can access the query params in both GET and POST

I think your form is not sending data as intended to the API endpoint. That's why it is returning empty object.

You can check this. Install postman if you don't have it and run:

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. It is often used when uploading a file or when submitting a completed web form. In contrast, the HTTP GET request method retrieves information from the server.

In your form please add this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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