sending html form data to node js

2019-08-18 22:09发布

I have the following code

    <!--index.html-->

  <form id = "lang" action="/myform" method="POST" >
    <input type="text" name="mytext" required />
    <input type="submit" value="Submit" />
</form>

and

//index.js

  var fileServer = new(nodeStatic.Server)();

  var app = http.createServer( function(req, res){

  fileServer.serve(req, res); 

}).listen(port);

var io = socketIO.listen(app);

io.sockets.on('connection', function(socket) {

  console.log('recieved connection ');
  // convenience function to log server messages on the client

How do I send data in the textbox with id "lang" over to index.js and store it in some variable?

using express by placing it as a parameter in http.createServer() and executing filsServer.serve(req, res) in a callback:

express = require('express');
app2 = express();
http = require('http');

    app2.post('/myform', function(req, res){

    console.log(req.body.mytext); 

  });

var app = http.createServer(app2, function(req, res){

 fileServer.serve(req, res);  

}).listen(8082);

this obviously wouldn't work because I need the index.html page to load to fill in the form to begin with and by executing the code above, the program is expecting some form data even before the html page can load.

Is there another way I can send the data?

1条回答
别忘想泡老子
2楼-- · 2019-08-18 22:55

I got it to work. Here's the code:

var express = require('express');
var app2 = express(); 
var bodyParser = require("body-parser");
var path = require('path');
var socketIO = require('socket.io');

app2.use(bodyParser.urlencoded({ extended: false }));
app2.use(bodyParser.json());

var app = http.createServer(app2);
`var io = socketIO.listen(app);`

app2.use( express.static(__dirname));

app2.post('/form', function(req, res){

  var lang = req.body.mytext;
  console.log( req.body.mytext);
  res.send(lang);
});

app.listen(8081);

Despite having created a server using express, I still needed to create the server using the HTTP module because an express server doesn't work with the socket.io module.

And I had used the express server to take care of my static files.

查看更多
登录 后发表回答