4

Hey I am trying to send the post request using express and node and here is my code.

index.html

<html>

<head>
    <title>Test</title>
</head>

<body>
    <form action="/form" method="POST" enctype="multipart/form-data">
        <input type="text" name="imagename"></input>
        <input type="submit" name="submit" value="submit"></input>
    </form>
</body>

</html>

My app.js file is given below:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
   extended: true
}));
app.use(bodyParser.json());

app.post('/form', function(req, res){
 res.setHeader('Content-Type', 'application/json');
 setTimeout(function(){
     res.send(JSON.stringify({
        imagename: req.body.imagename || null

    }));
  }, 1000);
});

Now I should get the output as imagename: //value added in the form if true or else null. And I am always getting a null value. I tried to log the value of req.body.imagename and I am getting undefined instead of the value that I inserted in the form. Any help would be appretiated.

2 Answers 2

7

You have to add the body-parser to your Express's app.

var app = express();
var bodyParser = require('body-parser');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

However, I've seen that you've declared your form with the enctype='multipart/formdata'. This is usually used to make file uploads, if it's really what you want, you're going to need to use another parser for it.

Sign up to request clarification or add additional context in comments.

2 Comments

I am trying to add a file and so I have used multipart/formdata. and I have included the two lines for bodyparser, just forgot to copy here. But because nothing was working I thought that first lets make the text working and then I will look into file and commented the file upload part. Thanks.
@JonathanLonowski and Edmundo Rodrigues Thanks a lot for your feedback. I was able to send the data when I removed the multipart from the form. Now I will try and use mulder and hope that works with the files. Cheers.
2

You required 'body-parser' middleware, but forgot to use it in your express app.

app.use(bodyParser.urlencoded())

and you don't need this one

enctype="multipart/form-data"

1 Comment

I already had the app.use(bodyParser.urlencoded()) in my code just forgot to copy here. and I need the second part because I will be using file uploads in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.