Powisss
Powisss

Reputation: 1142

JS HTTP post YAML

I am unable to post a yaml throught http in js. The code works when I used JSON.stringify(text) for body and have content-type application/json. If I use YAML stringify, body on server side is just {}. I have areatext where I enter a text (like yaml format) in html e.g.

martin:
  name: Martin D'vloper
  job: Developer
  skill: Elite

Client:

$('#create-yaml2').on('click',async function () {
    var text = $('#yaml-create').val();
    // console.log(text)
    var textYAML = YAML.stringify(text);
    var options = {
      hostname: 'myhostname',
      port: 80,
      path: `/api/postyaml`,
      method: 'POST',
      body: textYAML,
      headers: {
        'Content-Type': 'text/x-yaml'
      }
    };
    var executeReq = http.request(options);
    executeReq.write(textYAML);
    executeReq.end();
  });

EDIT: Function in server side, that prints not an empty {} when posting JSON.

exports.functionCalled = async function (req, res) {
    console.log('\n\n\n\n')
    console.log(req.body)
    console.log('\n\n\n\n')
    try {
        res.send(`RECEIVED`);
      } catch (upgradeErr) {
        res.status(422).json({
          message: `Failed`,
          error: upgradeErr
        });
    }
}

Upvotes: 0

Views: 1568

Answers (2)

Maksym Rudenko
Maksym Rudenko

Reputation: 746

You already have a string coming from HTML, so you don't need to call YAML.stringify once again - text is already a string.

$('#create-yaml2').on('click',async function () {
    var text = $('#yaml-create').val();
    // console.log(text)
    var textYAML = text;
    var options = {
      hostname: 'myhostname',
      port: 80,
      path: `/api/postyaml`,
      method: 'POST',
      body: textYAML,
      headers: {
        'Content-Type': 'text/x-yaml'
      }
    };
    var executeReq = http.request(options);
    executeReq.write(textYAML);
    executeReq.end();
  });

You may want to do something like

$('#create-yaml2').on('click',async function () {
    var text = $('#yaml-create').val();
try {
  YAML.parse(text)
} catch(e) {...}

...
send request

to make sure there was a valid YAML provided

Upvotes: 1

Quentin
Quentin

Reputation: 944204

YAML.stringify converts a JavaScript data structure to a string containing YML.

You don't have a JavaScript data structure, you just a string containing YML.

Almost. You have an error in it. You can't use a raw ' in a YML string that isn't quoted.

So:

Fix your YML:

martin:
  name: "Martin D'vloper"
  job: Developer
  skill: Elite

Don't double encode it:

var textYAML = $('#yaml-create').val();

Upvotes: 0

Related Questions