title: Unable to insert a record into ElasticSearch using node.js http.request - MapperParsingException[failed to parse]
body: <p>Trying to insert a record into ElasticSearch using node.js's <strong>http</strong> module  (<strong><em>not</strong> using 3rd party modules</em>)</p>
  
  <p><strong>Setup</strong>: running instance of ElasticSearch locally on port <strong>9200</strong> (default)</p>
  
  <p>Node.js Code:</p>
  
  <pre><code>var querystring = require('querystring'); // to build our post string
  var http = require('http');
  
  // Build the post string from an object
  var data = querystring.stringify({
    "text" :"hello world"
  });
  
  // An object of options to indicate where to post to
  var post_options = {
      host: 'localhost',
      port: '9200',
      path: '/twitter/tweets/1',
      method: 'POST',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(data)
      }
  };
  
  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
      });
  });
  
  // post the data
  post_req.write(data);
  post_req.end();
  </code></pre>
  
  <p>I get the following <strong>Error</strong>:</p>
  
  <pre><code>{"error":"MapperParsingException[failed to parse]; nested: 
  ElasticsearchParseException[Failed to derive xcontent 
  from (offset=0, length=18): [116, 101, 120, 116, 61, 104, 
  101, 108, 108, 111, 37, 50, 48, 119, 111, 114, 108, 100]]; ",
  "status":400}
  </code></pre>
  
  <p>But doing the following <strong>CURL</strong>s works as expected:</p>
  
  <pre><code>curl -XPOST 'http://localhost:9200/twitter/tweet/1' -d '{"message" : "hello world"}'
  </code></pre>
  
  <p>I Looked at the following StackOverflow questions which have similar error messages:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/16707072/getting-error-mapper-parsing-exception-while-indexing">Getting error mapper parsing exception while indexing</a></li>
  <li><a href="https://stackoverflow.com/questions/11017543/elasticsearch-parse-exception-error-when-attempting-to-index-pdf">Elasticsearch Parse Exception error when attempting to index PDF</a></li>
  <li><a href="https://stackoverflow.com/questions/27355553/elasticsearch-error-mapperparsingexception-failed-to-parse">ElasticSearch Error: MapperParsingException failed to parse</a></li>
  </ul>
  
  <p>Neither of these answered my question.</p>
  
  <p><em>Any</em> help much appreciated. <strong><em>Thanks</em></strong>!</p>
  
  <p><strong>Note</strong>: I am <em>deliberately</em> trying to use the ElasticSearch REST API using <strong><em>only Node.js Core</em></strong> (<em>no 3rd party</em>) modules (please don't suggest using <strong>elasticsearch-js</strong> or <strong>es</strong> or <strong>request</strong>, etc )</p>