Pritesh Mahajan
Pritesh Mahajan

Reputation: 5154

Set content-type header to json for request.post

I am using "hackathon-starter" node bunch for my project. In this build when I try to call a API from request.post it will take "Content type 'application/x-www-form-urlencoded;charset=utf-8' header for all API. I have tried to change header from API calling but it will take only

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

header for all API. I have tried below code. I want to set application/json for all API.

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)
    });

My error message on console.

{"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"}

Upvotes: 3

Views: 7510

Answers (1)

Farid Nouri Neshat
Farid Nouri Neshat

Reputation: 30420

I guess you need to use json option instead based on your requirements:

  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)
});

From the options documentaion:

json - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.

Upvotes: 7

Related Questions