Node.js - How to send data from html to express

前端 未结 2 1153
小蘑菇
小蘑菇 2020-11-29 16:32

this is form example in html:





CSS3 Contact Form
&         


        
2条回答
  •  迷失自我
    2020-11-29 16:52

    Using http.createServer is very low-level and really not useful for creating web applications as-is.

    A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

    When you have, you can create a basic application to handle your form:

    var express = require('express');
    var bodyParser = require('body-parser');
    var app     = express();
    
    //Note that in version 4 of express, express.bodyParser() was
    //deprecated in favor of a separate 'body-parser' module.
    app.use(bodyParser.urlencoded({ extended: true })); 
    
    //app.use(express.bodyParser());
    
    app.post('/myaction', function(req, res) {
      res.send('You sent the name "' + req.body.name + '".');
    });
    
    app.listen(8080, function() {
      console.log('Server running at http://127.0.0.1:8080/');
    });
    

    You can make your form point to it using:

    The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

提交回复
热议问题