Traccar API position returns in XML form

A Y4 years ago

I am using this code in node.js to get the positions:

const server_url = "localhost";
const route_positions = "/api/positions";
const http = require("http");
const fs = require('fs')

function positions(id) {
  const options = {
    host: server_url,
    path: route_positions + "?deviceId=" + id + "&from=2020-07-09T18:30:00Z&to=2020-07-22T18:30:00Z",
    port: 8082,
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Basic " + Buffer.from(user + ":" + password).toString('base64')
    },
  };
  http
    .request(options, function (res) {
      console.log("STATUS: " + res.statusCode);
      console.log("HEADERS: " + JSON.stringify(res.headers));
      res.setEncoding("utf8");
      res.on("data", function (chunk) {
        console.log("BODY: " + chunk);
        fs.appendFile('./server/data/testpos.json', chunk, (err) => {
          if (err) {
            console.error(err)
            return
          }
          //file written successfully
        })
      });
    }).end();
}

Unfortunately, this code returns the position in XML format instead of the wanted JSON format.
I am not sure how to get the default (JSON) response.

Anton Tananaev4 years ago

You need to include Accept header in your request.

A Y4 years ago

Works like a charm. Thank you!