0
arr.push({type: 1, articul: articul, id: id, size: size, price: price});

Скрипт передающий данные:

$.ajax({
    type: "POST",
    url: "http://localhost:8888/update/",
    async: false,
    dataType: "json",
    success: function (req) {
        console.log('req'+ req);
    },
    //json: JSON.stringify(arr)
    data: JSON.stringify(arr),
    json: true
});

Серверная часть:

app.post('/update', (req,res) =>{   
//res.send(`user: #${req.params.id}`);
//const res_data = JSON.parse(req.body);
//console.log(qs.parse(req.body));
//console.log(JSON.parse(req.body.key));
var arr = [];
Object.keys(req.body).forEach(function (key, value) {
    //console.log(key);
    arr = key.split('},{');
    //arr.push(JSON.parse(key));
});
console.log(arr);
//arr.push({id: 1, articul: '00000000', size: 777, price: 350.00});
//console.log(arr[0].size);
//makeAllUpdate(arr);
res.send('http: ok');

});

Выхлоп:

console.log(req.body) :{'{"type":1,"articul":"53020000","id":"23","size":"80","price":"58.50"}': ' '}

Если сделать два arr.push(...) с одинаковыми данными , то в console.log(req.body) выхлоп:

{'{"type":1,"articul":"53020000","id":"23","size":"80","price":"58.50"},{"type":1,"articul":"53020000","id":"23","size":"80","price":"58.50"} ': ''}

В вкладке network -> headers -> Format Data:

[{"type":1,"articul":"53020000","id":"23","size":"80","price":"58.50"},{"type":1,"articul":"00005301","id":"102","size":"80","price":"98.90"}]:

Request Headers:

Accept:application/json, text/javascript, /; q=0.01 Accept-Encoding:gzip, deflate, br

т.е получается поле key заполняется, а val нет и при использовании JSON.parse ошибка, что говорит о том что что-то не так. Ссылка на git: Весь код

[![Скрин из IDE][2]][2]

[![Скрин из браузера][3]][3]

Изменил код $ajax(...) на

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
               { "position": "235.1944023323615", "markerPosition": "19" },
               { "position": "42.5978231292517", "markerPosition": "-3" }];
        //console.log(JSON.stringify(arr));
        //var jsonObj = {'key':'value'};
        //console.log(JSON.stringify(jsonObj));
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: 'http://localhost:8888/update/',
            dataType: 'json',
            success: function (req) {
                console.log('req'+ req);
            },
            //json: JSON.stringify(arr)
            //data: JSON.stringify({b : 4})
            data: JSON.stringify({ 'Markers' : markers })
        });
    });

});

console.log(req.body):

    { Markers:
   [ { position: '128.3657142857143', markerPosition: '7' },
     { position: '235.1944023323615', markerPosition: '19' },
     { position: '42.5978231292517', markerPosition: '-3' } ] }

Ответ корректный, ошибка возникает при попытке:

var data1 = JSON.parse(req.body);
SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
16
  • Не знаю, как оно на самом деле в jQuery, но сильно подозреваю, что если указано json : true, то JSON.stringify будет лишним.
    – Yaant
    16 мар 2019 в 8:57
  • Возможно, но не влияет в данном случае, я пробовал разные варианты. 16 мар 2019 в 9:00
  • Ну и в express'е не будет лишним указать express.json() в качестве middleware.
    – Yaant
    16 мар 2019 в 9:01
  • app.use(bp.json()); (где bp - body parser) уже было указано. 16 мар 2019 в 9:27
  • console.log(req.body); ---> { '{"type":1,"articul":"53020000","id":"23","size":"80","price":"58.50"}': ' ' } что говорит о том что что-то не так. 16 мар 2019 в 9:28

1 ответ 1

0

    $(".update").click(function () {

        arr = [];
        $('.table > tbody > .rows').each(function (tr) {
            //console.log('row' + $(this).html());
            if ($(this).children().find('.icheckbox').is(":checked")) {
                var row = ($(this).attr('id')).substring(2,5);
                //console.log('row' + row);
                var articul = $(this).find('.art'+row).text();
                //console.log('art ' + articul);
                var id = $(this).children().find('.biginput').attr('pdb');
                
                var size = $(this).children().find('.my_size').val();
                //console.log('pdb ' + id);
                var price = $(this).find('.c_price').text();
                //console.log('price ' + price);

                if(id !== '')arr.push({type: 1, articul: articul, id: id, size: size, price: price});

            }
        });
        
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: 'http://localhost:8888/update/',
            dataType: 'json',
            success: function (req) {
                console.log('req'+ req);
            },
            data: JSON.stringify({ Markers : arr })//JSON.stringify({ Markers: markers }),
        });
    });

node.js

const urlencodedParser = bp.urlencoded({ extended: false });
const jsonParser = bp.json();

app.use(bp.json({ type: 'application/*+json' }));

...

app.post('/update',jsonParser, (req,res) =>{   

    Object.values(req.body.Markers).forEach(function (value) {
         console.log(value.size);
    });

    makeAllUpdate(req.body.Markers);
    res.send('http: ok');
});
Правда JSON.parse все равно вываливается, но я достал данные в цикле

Ваш ответ

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

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