Home > Enterprise >  undefined output from body-parser
undefined output from body-parser

Time:12-16

I'm trying to get the user input from the client side to the server side using body-parser in node.js. I am using express as a base of my application.

Here is the server side code:

app.post('/register', urlencodedParser, (req, res) => {
console.log("The text is: "   req.body.url)})

Here is the html form, from which I'm trying to extract the input:

 <form  action="/register" method="POST">
            <div >
                <div >
                    <h5  id="addModalLabel">Add comics</h5>
                    <button type="button"  data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div >
                    <div  role="alert">
                        Curently the amount of URL's supported is limited. Check out info page for more detailed
                        info.
                    </div>
                    <div >
                        <label for="url">URL of comics</label>
                        <input type="text"  id="url" aria-describedby="urlHelp"
                            placeholder="Enter URL">
                        <small id="urlHelp" >For detailed guide on how to find URL go to
                            info
                            page.</small>
                    </div>
                    <div >
                        <label for="exampleFormControlTextarea1">Description</label>
                        <textarea  id="description" rows="3"></textarea>
                    </div>
               
                </div>
                <div >
                    <button type="button"  data-bs-dismiss="modal">Close</button>
                    <button type="submit" >Add</button>
                </div>
            </div>
        </form>

The problem is that the output is undefined. I'm new to node.js so this might be an easy question, but I'm stuck for quite some time so please don't juge.

CodePudding user response:

Within the form's input fields, the way node.js rexognizes these is by specifying the name field on the input on the front end. so like this:

<input type="text"  id="url" name="url" aria-describedby="urlHelp"

now on the backend since your route is a .post function, you can access it using req.body.url, which you are already doing!

CodePudding user response:

You should add a name attribute to your input: <input name="url" … />. Only form elements with a name attribute will have their values passed when submitting a form.

  • Related