0

I created a UI to read, write and update a config file using HTML but I am not able to save new JSON object to my existing config file.

So I need to post JSON object from HTML file to nodejs server

JAVASCRIPT

 var testJson = { name: "mufashid" }
        $.ajax({
            url: 'http://localhost:3000/test/config',
            type: 'POST',
            dataType: 'json',
            data: { o: JSON.stringify(testJson ) }, // bags collection value what your goging to send to server 
            // crossDomain: true,
            success: function (data) {
                alert('Success!')
            },
            error: function (jqXHR, textStatus, err) {
                //show error message
                alert('text status ' + textStatus + ', err ' + err)
            }
        });

nodejs


app.post('/test/config', function (req, res) {
    // console.log(res);
    console.log(req)

})

Need to update the config file with the new value when pressed the save button.

Mufshid
  • 55
  • 2
  • 7

2 Answers2

-1

You missed contentType: "application/json" in your javascript code.

var testJson = { name: "mufashid" }
        $.ajax({
            url: 'http://localhost:3000/test/config',
            type: 'POST',
            contentType: "application/json",// you missed this line.
            dataType: 'json',
            data: JSON.stringify({ o: testJson }), // IMportant!!!!!!
            // crossDomain: true,
            success: function (data) {
                alert('Success!')
            },
            error: function (jqXHR, textStatus, err) {
                //show error message
                alert('text status ' + textStatus + ', err ' + err)
            }
        });
lx1412
  • 1,160
  • 6
  • 14
-1

Please find the below code. Content type was missing

$.ajax({
    url: 'http://localhost:3000/test/config',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify({
      o: testJson
    }),
    // crossDomain: true,
    success: function (data) {
      alert('Success!')
    },
    error: function (jqXHR, textStatus, err) {
      //show error message
      alert('text status ' + textStatus + ', err ' + err)
    }
  });

Routes

app.post('/test/config', function (req, res) {
  console.log(req.body.o);
})
XCEPTION
  • 1,671
  • 1
  • 18
  • 38