M
M
Max Donchenko2016-07-31 21:13:10
JavaScript
Max Donchenko, 2016-07-31 21:13:10

Sending data from a form with further processing by NodeJS?

Good day!
I am writing my first project using:

  • NodeJS
  • gulp
  • SASS
  • Jade
  • and more...

All the problems that were encountered were easily (and sometimes not very) googled.
Now I'm stuck on a point that many people will think is obvious, but I can't seem to resolve it. The point is this:
I want to transfer the data that the user enters (screenshot 1, p. 1,2,3) to the server and save it as a JSON file (screenshot 2, p. 2; screenshot 3).
When using the code (lines 7-22, screenshot 2), when you click on "Submit", "Hello world" is displayed on the opened page, and the selected buttons are displayed in the console (screenshot 2, p. 3, but without input values), which means , the code runs without errors. In addition, I would like to perform all actions on one port and using one server (without using the crutch that I have now; screenshot 2, item 4).
On the web, I found many tutorials on processing this data, but in all that I saw, something like This syntax is no longer suitable, because the current version of Express is 4. Tell me: 1) What is the best way to deal with routing? 2) Which Gulp plugin is suitable for these purposes? 3) How to read in addition to the values ​​of the selected buttons also the values ​​of input(text)? 4*) Bonus question: what if the compiler swears when using the ES6 syntax in the "serve.js" task file? (because of this, I had to change arrow-functions and interpolation for the old version of ES). Screenshot 1: Screenshot 2: Screenshot 3:
app.get("/some/route", function(req, res){...})
2yerM1V6zNE.jpg
YI_H_6yVIg4.jpg
FO7eSlE-EJk.jpg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
olegshilov, 2016-08-01
@olegshilov

import express from 'express';
import bodyParser from 'body-parser';

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => {
  res.sendStatus(200);
});

app.post('/', (req, res) => {
  console.log(req.body);
  res.json({
    status: 200,
    message: 'Ok'
  });
});

const server = app.listen(config.listen, (error) => {
  if (error) {
    console.error(error);
    process.exit(1);
    return;
  }

  const { address, port } = server.address();

  console.log(`Listening ${address}:${port}`);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question