1

I am trying to implement a html form which takes input and sends it to node js server but the html form is not sending any data to node js. It makes a request but no form data is sent.

I have an index.html file

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Input Form</title>
</head>
<body>
    <h1>Send a message:</h1>
    <form action="http://localhost:3000/action" method="POST">
        <label for="data">Message:</label>
        <input type="text" id="data" placeholder="Enter your message" name="text"/>
        <input type="submit" value="Send message" />
    </form>
</body>
</html>

and a node js file

//Modules
const fs = require ('fs');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const http = require('http');
const actionRoute=require('./routes/action')
const server = http.createServer(app)
app.use(express.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.all('/',(req,res)=>{
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(fs.readFileSync('./public/index.html'))
})
const hostname = 'localhost';
const port = 3000

app.post('/action',(req,res)=>{
    console.log(req.body)
    res.statusCode=200;
    res.end("thnx")
})


server.listen(port , hostname,function(){
    console.log('Server running at http://'+hostname+':'+port);
});

Directory structure:

|
|-index.js
|-public
|--index.html

In the post route the req.body is empty it prints{}

0

1 Answer 1

2

I tried the exact same code and it worked perfectly. One possible reason why it didn't work for you is that the html form is on a different host, cross-origin requests aren't allowed by default. To allow all origins:

  1. Install cors from npm

    npm install cors

  2. Use CORS middleware for your route

const cors = require('cors');
.
.
.
app.post('/action', cors(), (req, res) => {
   console.log(req.body)
   res.statusCode=200;
   res.end("thnx")
});

Check express official documentation for more

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

2 Comments

Is this due to my directory structure I have added my dir structure in question
No, as long as it's in the same host, this won't be a problem. Tried it with the same structure and it works fine. Also consider using app.use(express.static('public')); for serving static files.

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.