S
S
srnsdlmtn2016-06-03 14:39:59
Node.js
srnsdlmtn, 2016-06-03 14:39:59

How to get the value of a node.js variable?

It is not possible to take the value from the form field, the form
itself is like this:

<html>
    <head></head>
    <body>
        <form method="POST" action="/myaction">
            <input type="text" id="txt" name="name">
            <input type="submit">
        </form>
    </body>
</html>

a single node.js file looks like this:
var http = require('http'),
    fs = require('fs'),
    qs = require('querystring'),
    express = require('express'),
    app = express();

fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        app.post('/myaction', function(req, res){
            var word = req.query.name;
            var event = {
                title: word,
                date: "20.20.20"
            };
            var str = JSON.stringify(event);
            fs.writeFileSync('test.txt', str);
        });
        
        response.end();  
    }).listen(8000);
});

the problem is like this:
app.post('/myaction', function(req, res){
            var word = req.query.name;
            var event = {
                title: word,
                date: "20.20.20"
            };
            var str = JSON.stringify(event);
            fs.writeFileSync('test.txt', str);
        });

if I just write values ​​to var event, then they are saved to this file, if I do as it is written above, nothing works, although the form is submitted, please advise how to make it work.
I googled a lot, in Russian, in English, I didn’t find anything sensible or understandable for myself

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Wolf, 2016-06-03
@srnsdlmtn

1. This is exactly the case when you should use synchronous methods.
2. Your express knows nothing about the server and access to it is not transferred. Therefore, nothing works. Read how to work with it.

var fs = require('fs');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

var html = fs.readFileSync('./index.html');

app.use(bodyParser.urlencoded({}));

app.get('/', function(req, res) {
  res.writeHeader(200, {"Content-Type": "text/html"});  
  res.end(html);  
});

app.post('/myaction', function(req, res){
  var word = req.body.name;
  var event = {
    title: word,
    date: "20.20.20"
  };
  var str = JSON.stringify(event);
  fs.writeFile('test.txt', str, function(err) {
    if(err) console.error(err);
    else res.end("Success");
  });
});

app.listen(3000);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question