简体   繁体   中英

HTML form not sending data to node js

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

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

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