How to make an HTTP POST request on node js

2019-08-23 18:58发布

问题:

The following is the server:

const Bpmn = require('bpmn-engine');

const processXml = `
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <process id="theProcess" isExecutable="true">
    <startEvent id="start" />
    <exclusiveGateway id="decision" />
    <endEvent id="end1" />
    <endEvent id="end2" />
    <sequenceFlow id="flow1" sourceRef="start" targetRef="decision" />
    <sequenceFlow id="flow2" sourceRef="decision" targetRef="end1">
      <conditionExpression xsi:type="tFormalExpression" 
language="JavaScript"><![CDATA[
      this.variables.input <= 50
      ]]></conditionExpression>
    </sequenceFlow>
    <sequenceFlow id="flow3" sourceRef="decision" targetRef="end2">
      <conditionExpression xsi:type="tFormalExpression" 
language="JavaScript"><![CDATA[
      this.variables.input > 50
      ]]></conditionExpression>
    </sequenceFlow>
  </process>
</definitions>`;

const engine = new Bpmn.Engine({
  name: 'exclusive gateway example',
  source: processXml
});

engine.once('end', (definition) => {
  if (definition.getChildActivityById('end1').taken) throw new Error('<end1> 
was not supposed to be taken, check your input');
  console.log('TAKEN end2', definition.getChildActivityById('end2').taken);
});

function sendEvent(value){
    engine.execute({
  variables: {
    input: value
  }
}, (err, definition) => {
  console.log('Bpmn definition definition started with id', 
definition.getProcesses()[0].context.variables.input.value);
  console.log('sent event' + value);
  console.log(engine.getState())
});
}

i = 0;
//hello.js
module.exports = (req, res, next) => {
  //res.header('X-Hello', 'World')
  //console.log(req);
  if(!i++){
      sendEvent(52);
  }
  console.log(engine.getState())
  next()
}

The server above has been created using that package adding middlewares https://www.npmjs.com/package/json-server The number 52 in the function "sendEvent" is an example. I have to take this value from an http post. How can I do that?

回答1:

Use the request library:

var request = require('request');

request.post(
    'http://www.example.com',
    { json: { key: 'value' } },
    function (error, response, body) { 
            console.log(body)
    }
);