node.js - 将 request.post 的内容类型 header 设置为 json

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

我正在为我的项目使用“hackathon-starter” Node 组。在此构建中,当我尝试从 request.post 调用 API 时,它将采用所有 API 的“Content type 'application/x-www-form-urlencoded;charset=utf-8' header 。我已尝试通过 API 调用更改 header ,但只需要

Content type : 'application/x-www-form-urlencoded;charset=utf-8'

所有 API 的 header 。我试过下面的代码。我想为所有 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"}

最佳答案

我猜你需要根据你的要求使用 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 - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.

关于node.js - 将 request.post 的内容类型 header 设置为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41739866/

相关文章:

c++ - ToCString 的 header 在哪里,或者如何将参数转换为 cstrings?

node.js - 配置 Sails.js 以使用 Vash View 引擎

javascript - 如何在 React Native 和 Node 中计算校验和?

javascript - 图表显示不正确

json - 如何在服务器端最好地验证JSON

php - 回调 API 服务需要什么才能通过 SSL 连接到我的服务器?

api - 何时选择关联而非查询

c++ - 带有源文件的头文件 C++

html - 横幅图像放置和比例

php - 标题被忽略