How to send data from html to node.js

前端 未结 2 2086
盖世英雄少女心
盖世英雄少女心 2021-02-06 01:53

I\'m a rookie in web languages so please do excuse me if my question is foolish. Basically I\'m trying pass data from html-form to node.js server but e

2条回答
  •  不思量自难忘°
    2021-02-06 02:20

    I would highly suggest using a framework like Express for a more pleasant Node.js interactions. So the first thing you would have to do is install it:

    npm install express
    

    And for my example, I'll install an additional middleware, called body-parser.

    npm install body-parser  // this allows us to access req.body.whatever
    

    After that make a simple server to handle your POST requests, like this:

    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    
    app.use(bodyParser.urlencoded({ extended: true })); 
    
    app.post('/example', (req, res) => {
      res.send(`Full name is:${req.body.fname} ${req.body.lname}.`);
    });
    
    const port = 8080;
    
    app.listen(port, () => {
      console.log(`Server running on port${port}`);
    });
    

    And here is our HTML form: So we're sending our data to our localhost [http:// 127.0.0.1], port 8080 and a route of /example --> All that was configurated in our little Express server

    First name:
    Last name:

提交回复
热议问题