0

Почему этот код не работает?

Все же вроде верно написано!

index.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <title>
    Test application!
    </title>
  </head>
  <body>
    <form action="index.html" method="POST">
        <input type="text" name="first_name" />

        <input type="submit" value="Send" />
    </form>
  </body>
</html>

server.js:

var fs = require("fs");
var index = fs.readFileSync('./index.html');
var http = require('http');
var app = require('express')(),
    bodyParser = require('body-parser');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
    res.end(index);
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

app.use("/index.html", bodyParser.urlencoded({
    extended: false
}));

app.post("/index.html", function(req, res, next) {

    console.dir(req.body);
    console.log(req.body);
    res.send('Your name is' + req.body.first_name);
});
7
  • А что ожидается от кода?
    – Dmytro
    30 апр 2018 в 6:01
  • Чтобы данные введенные в текстовое поле отправлялись на сервер,а потом возвращались на эту же страницу с сервера
    – ZeusBios
    30 апр 2018 в 6:02
  • А как Вы определяете, что данные не возвращаются назад?
    – Dmytro
    30 апр 2018 в 6:05
  • Я считал что они должны отобразиться на странице? или нет?
    – ZeusBios
    30 апр 2018 в 6:10
  • Ok. А как сделать чтобы они отображались на странице?
    – ZeusBios
    30 апр 2018 в 6:32

2 ответа 2

2

Скорее всего, потому что биндите сервер через http, а не через express.

С экспрессом обычно делается так:

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

// вместо http.createServer..., напишите просто
app.listen(8080, function () {
  console.log('Server running at http://127.0.0.1:8080/');
});

app.use('/index.html', bodyParser.urlencoded({ extended: false }));

app.get('/index.html', function(req, res, next) {    // при гете - отдаем файл
  res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/index.html', function(req, res, next) {   // при посте - строку с именем из реквеста
  res.send('Your name is ' + req.body.first_name);
});

RunKit endpoint

1

В качестве ответа на комментарий. Только я не парсил запрос, а просто вывел его в консоли. Ответ вернул произвольный.

const fs = require("fs"),
      http = require ("http"),
      url = require("url"),
      index = fs.readFileSync('./index.html'),
      port = 3000,
      server = http.createServer();

server.listen(port, function(){
    console.log("Сервер запущен по адресу localhost:"+port);
    console.log("*****************************************************************");
})

server.on("request", function(req, res){
    if (req.method == "GET") {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(index)
    } else if (req.method == "POST") {
        var data ="";
        req.on('data', function(chunk){
            data += chunk;
        })
        req.on("end", function(){
            console.log(data)
            res.writeHead(200, {"Content-Type": "text/plain"});
            res.end("Very good");
        });
    }
});

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.