1

Basically, I am trying to fetch data from MongoDB collection and read it with d3.json.

First, I sent data to a specific route in main index.js.

// fetch data
app.get('/fetch.json', (req, res) => {
  Data.find({})
    .then(sample => {
      res.json(sample)
    })
})

If I check localhost:3000/fetch.json, my data is in there as an array with each object.

[{...},{...},{...},{...}]

However, when I tried to read data with d3, I got a Syntax Error:

Uncaught (in promise) SyntaxError: Unexpected token T in JSON at position 0

This is the code that attempts to read data:

// load data
d3.json('./fetch.json', (err, data) => {
  if (err) {
    throw err
  }
  data.map((t) => {
    console.log(t)
  })
})

I tried different approaches, considering this answer: Convert Mongoose docs to json. However, I got the same result.

Am I missing something inside main index.js or I need to fetch data in a different way?

Ramiro Tormenta
  • 601
  • 1
  • 8
  • 18
  • Your request says `d3.json('./fetch.json'` and likely should be `d3.json('/fetch.json'` or whatever the "full path" to the resource really is rather than preceding with a "dot" `.`. The `Unexpected token T` message is basically the first letter of the phrase `The requested resource was not found` or essentially a `404` error. In breif, check your browser network requests and you will see the `404`. So fix the path to where the resource actually is. – Neil Lunn Nov 16 '17 at 02:42
  • @NeilLunn Is a different question and the "dot" doesn't create conflict. The "dot" means `current directory`, so the path doesn't need to be fix. I already did tests with different approaches. The problem, for I can understand, is with `d3` new versions installed with npm, and using `require('d3'`). This problem doesn't show up using normal `` on html file. – Ramiro Tormenta Nov 16 '17 at 03:12
  • Point is that you have a `404`, hence the JSON parse error. I had the d3 docs up a moment ago, but the basics are it's just an XHTTP request that "chains" a `JSON.parse` before returning the data. Check your network tab in your browser debugging. The resource will not be found, so you need to point it to wherever the correct location is. That's the cause and that's the fix. And yes we do understand "relative" to "absolute" paths and what they mean. But a `404` "is what it is" regardless of where you "think" the endpoint is located. – Neil Lunn Nov 16 '17 at 03:14
  • I have tried with local files using the exactly path. Why jsonfile is read when I use normal ` – Ramiro Tormenta Nov 16 '17 at 03:18
  • You're asking the wrong question and therefore looking in the wrong place. Go and actually look at your network requests in the browser dev tools like I told you. The JSON parse error if from exactly the string response I have told you. Work out how to talk to your backend and then you will resolve the issue. – Neil Lunn Nov 16 '17 at 03:23

0 Answers0