将content-type标头设置为request.post的json

时间:2017-01-19 10:46:55

标签: node.js api header http-post content-type

我正在使用" hackathon-starter"节点束为我的项目。在此构建中,当我尝试从request.post调用API时,它将采用"所有API的内容类型'application/x-www-form-urlencoded;charset=utf-8'标头。我试图从API调用更改标题,但它只需要

  

内容类型:' application / x-www-form-urlencoded; charset = utf-8'

所有API的标头。我试过下面的代码。我想为所有API设置 application / json

var querystring = require('querystring');
      var request     = require('request');

      var form = {
        "userType": req.body.type,
        "userName": req.body.mobile,
        "email": req.body.email,
        "name": req.body.name,      
        "password": req.body.password
      };  

      var formData = querystring.stringify(form);
      var contentLength = formData.length;
      request.post({
          headers: {'content-type':'application/json'},
          url:'mylink',
          form:    formData // I have tried form as well.
      },function(error, response, body){
      console.log(body)
    });

我在控制台上的错误消息。

{"timestamp":1484822264270,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'application/x-www-form-urlencoded;charset=utf-8' not supported","path":"mylink"}

1 个答案:

答案 0 :(得分:6)

我猜您需要根据您的要求使用json选项:

  var form = {
    "userType": req.body.type,
    "userName": req.body.mobile,
    "email": req.body.email,
    "name": req.body.name,      
    "password": req.body.password
  };  

  request.post({
      url:'mylink',
      json: form,
  },function(error, response, body){
  console.log(body)
});

来自选项文件:

  

json - 将body设置为值的JSON表示并添加   内容类型:application / json标头。另外,解析   响应机构为JSON。