在nodejs中使用正文发出发布请求

时间:2019-07-04 08:56:09

标签: node.js api request

我正在使用nodeJS与API进行通信。 为此,我使用了发帖请求。

在我的代码中,我使用表单数据传递变量,但出现错误400。当我尝试放入body时,出现错误,表明变量未定义。

这是API:https://developer.hpe.com/api/simplivity/endpoint?&path=%2Fdatastores

我的请求:

async function postCreateDatastore(url, username, password, name, clusterID, policyID, size, token) {
    console.log (name, clusterID, policyID, size)
    var options = {
        method: 'POST',
        url: url + '/datastores',
        headers: {
            'Content-Type': 'application/vnd.simplivity.v1.1+json',
            'Authorization': 'Bearer ' + token,
        },
        formdata:
        {
            name: name,
            omnistack_cluster_id: clusterID,
            policy_id: policyID,
            size: size,
        }
    };
    return new Promise(function (resolve, reject) {
        request(options, function (error, response, body) {
            if (response.statusCode === 415) {
                console.log(body);
                resolve(body);
            } else {
                console.log("passed");
                console.log(JSON.parse(body));
                resolve(response.statusCode);
            }
        });
    });
}

答案:

testsimon20K 4a298cf0-ff06-431a-9c86-d8f9947ba0ba ea860974-9152-4884-a607-861222b8da4d 20000
passed
{ exception:
   'org.springframework.http.converter.HttpMessageNotReadableException',
  path: '/api/datastores',
  message:
   'Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Object> com.simplivity.restapi.v1.controller.DatastoreController.createDatastore(javax.servlet.http.HttpServletRequest,com.simplivity.restapi.v1.mo.actions.CreateDatastoreMO) throws org.apache.thrift.TException,org.springframework.web.HttpMediaTypeNotSupportedException,com.simplivity.restapi.exceptions.ObjectNotFoundException,java.text.ParseException,java.io.IOException,com.simplivity.util.exceptions.ThriftConnectorException,com.simplivity.common.exceptions.DataSourceException',
  timestamp: '2019-07-04T08:51:49Z',
  status: '400' }

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我建议使用node-fetch发布您的数据。该软件包可让您使用ES6中的默认提取功能。

这是您的答案:

//require the node-fetch function
const fetch = require('node-fetch');

async function postCreateDatastore(url, username, password, name, clusterID, policyID, size, token) {
    console.log(name, clusterID, policyID, size);
    
    try {
      const response = await fetch(`${url}/datastores`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + token,
        },
        body: JSON.stringify({
          name,
          omnistack_cluster_id: clusterID,
          policy_id: policyID,
          size
        })
      });
    
      const json = await response.json();
    
      console.log(json);

      return json;
    }
    catch(e) {
      throw e;
    }
}