0

мне нужно отправить данные из формы на Node.js сервер

В данном коде видна функция которая собирает данные и отпраляет их на серевер предворительно засунув в json фармат

function mailSend(){

    // Country From 
    const e1 = document.getElementById("countryFrom");
    const countryFromValue = e1.options[e1.selectedIndex].value;

    // Country to 
    const e2 = document.getElementById("countryTo");
    const countryToValue = e2.options[e2.selectedIndex].value;

    // Type of Order 
    const orderType = checkboxInformation()

    // Information about cargo 

    const volume = document.getElementById('dshv_input').value

    const weight = document.getElementById('input1').value

    // Packing and quantity 
    const e3 = document.getElementById("packing_select");
    const packingType = e3.options[e3.selectedIndex].value;
    let textPacking = ""

    if(!(packingType === "Not_choice")) {
        const amount = document.getElementById('packing_input').value;

        textPacking = textPacking.concat("Packing type: ", packingType, ". Packing amount: ", amount);
    } else{
        textPacking = "Packing - NOT";
    }

    // More info 

    const moreInfo = document.getElementById('more_textrea').value

    // Contact information 
    const company = document.getElementById('companyName_input').value
    const name = document.getElementById('personName_input').value
    const phone = document.getElementById('phoneNumber_input').value
    const email = document.getElementById('email_input').value

    let allDataJSON  = {
        countryFromValue: countryFromValue,
        countryToValue: countryToValue,
        orderType: orderType,
        volume: volume,
        weight: weight,
        textPacking: textPacking,
        moreInfo: moreInfo,
        company: company,
        name: name,
        phone: phone,
        email: email
    }

    allDataJSON = JSON.stringify(allDataJSON);
    allDataJSON = JSON.parse(allDataJSON);



    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var myObj = xmlhttp.responseText;
            alert(myObj);
        }
    }

   ` console.log(allDataJSON);`

    xmlhttp.open("POST", "/mail");
    xmlhttp.setRequestHeader('Content-Type', 'application/json');
    xmlhttp.send(allDataJSON);

}

Последний console log выдаёт все данные корректно на стороне front-end

company: ""
countryFromValue: "Latvia"
countryToValue: "United States of America"
email: ""
moreInfo: ""
name: ""
orderType: (10) ["Type of order (transport)", "By ship - NO", "By auto - NO", "By combo transport - NO", "By train - NO", "By airo - NO", "By others - NO", "Insurance service - No", "Warehouse Service - No", "Custom Service - NO"]
phone: ""
textPacking: "Packing - NOT"
volume: ""
weight: ""
__proto__: Object

Код на back-end Node.js выглядтит таким образом: APP.JS

let express = require('express'),
    router = express.Router();

let app = express();
const path = require('path');
const bodyParser = require("body-parser");

const mainRoutes = require('./routes/main.js');
const serviceRoutes = require('./routes/service.js');

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

app.use('/', express.static(path.join(__dirname, 'public')));

app.use(mainRoutes);

app.use(serviceRoutes);

app.use('/',(req, res, next) => {
    res.redirect('/en');
  }); 

module.exports = app;

SERVICE.JS

let express = require('express');
const path = require('path');

const router = express.Router();

router.post('/mail', (req, res, next) => {
    const clientData = req.body;

    console.log(clientData);

    res.status(201).json({
        message: "OK",
        data: clientData
    });

});



module.exports = router;

проблема заключаеться в том что я не могу понять, почему сервер не может получить данные запроса

Можете помочь с решением проблемы AJAX запроса на Node.js

Ответ от сервера пустой массив:

{message: "OK", data: {}}
data: {}
message: "OK"

Заранее благодарен за ответ !!!!

4
  • 1
    Можно поинтересоваться что вы тут делаете allDataJSON = JSON.stringify(allDataJSON); allDataJSON = JSON.parse(allDataJSON); 28 июл 2020 в 16:15
  • Можете изменить ответ с ОК на окmail чтоб быть уверенным что это тот responce 28 июл 2020 в 16:29
  • Aziz Umarov, изменил okey на okeymail ( этот тот самый запрос, все хорошо, на стороне back-end-а тоже приходит пустой объект на строке console.log(clientData); перепроверил это ) 29 июл 2020 в 5:37
  • Aziz, Uzmarov, allDataJSON = JSON.stringify(allDataJSON); allDataJSON = JSON.parse(allDataJSON);, да здесь не много тафтологии, stringify (преобразует в JSON формат), parse находит и переписывает туже переменную (как написал в теле вопроса, в этом проблему не вижу, так как формат корректен, но можно убрать конечно) 29 июл 2020 в 5:41

1 ответ 1

0

Окей, я решил проблему. Для отпраки JSON файлов через ajax запрос на Node.js - необходимо использовать bodyParser.json([options]) на стороне сервера

Returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

А так же выстовить headers на front-end:

xmlhttp.setRequestHeader("Content-type", "application/json");

До этого подготовив данные через:

allDataJSON = JSON.stringify(allDataJSON);

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

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