0

I'm trying to get a json file using API (node.js express). When I run the below code, I've got the error (SyntaxError: Unexpected token < in JSON at position 0). I have no clue for the error.

The json file returns this.

[
  RowDataPacket { id: 1, name: 'test' },
  RowDataPacket { id: 2, name: 'test1' },
  RowDataPacket { id: 3, name: 'test2' },
  RowDataPacket { id: 4, name: 'test3' },
  RowDataPacket { id: 5, name: 'test4' },
  RowDataPacket { id: 6, name: 'test5' }
]



Main.js
I think res.json() causes this error, but I feel like the api.js returns json file correctly. How can I fix this issue?

import { useState, useEffect } from 'react'

function Main(){
    const [fetchData, setFetchData] = useState([])

    const test = () => {
        fetch(`/defg/test`)
        .then(res => res.json())
        .then(result => setFetchData(result))
    }
    return(
        <div>
            <h1>Main</h1>
            <button onClick={test}>GetData: {fetchData}</button>
        </div>
    );
} export default Main;


api.js

var express = require('express');
var router = express.Router();
const knex = require('../connection');


router.get('/test', function(req, res){
    knex.select('*').from('test')
    .then(data => res.send(data))
})

module.exports = router;


app.js

const express = require('express')
const app = express()
const mysql = require('mysql')
var bodyParser = require('body-parser')
var path = require('path')
var morgan = require('morgan')
const knex = require('./routes/connection');
var router = express.Router();

var router = require('./routes/abc');


app.use(morgan('dev'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(express.static(path.join(__dirname, 'static')))
app.use('/defg', router);


app.listen(8090, function() {
    console.log("running on port 8090")
})

module.exports = app;
coala
  • 11
  • 5
  • you are missing a `;` on the line before the return. – Hogan May 24 '22 at 03:31
  • Assuming `data` is an array then `res.send(data)` will send the string `"[object Object]"` -- literally an opening square bracket followed by lowercase "o" then the letter "b" etc. – slebetman May 24 '22 at 04:44

2 Answers2

0

Forgive me, I didn't read all of your code, but are you sure that's the JSON response? My Spidey sense says that since < is often the first character of an HTML or XML response, maybe that's what you're getting. Are you sure that's not being returned?

pixelearth
  • 13,674
  • 10
  • 62
  • 110
0

If you mean to return a JSON content-type, the easiest way is to leverage the dedicated method of the response in Express:

router.get('/test', function(req, res){
    knex.select('*').from('test')
    .then(data => res.json(data))    // <-- note the "json"
})

However, the JSON data you show on the post aren't valid: it misses the colon ":" character as separator between key (i.e. "RowDataPacket") and the value (i.e. the braces).

More likely, should be this:

[
  RowDataPacket: { id: 1, name: 'test' },
  RowDataPacket: { id: 2, name: 'test1' },
  RowDataPacket: { id: 3, name: 'test2' },
  RowDataPacket: { id: 4, name: 'test3' },
  RowDataPacket: { id: 5, name: 'test4' },
  RowDataPacket: { id: 6, name: 'test5' }
]
Mario Vernari
  • 6,649
  • 1
  • 32
  • 44
  • The `RowDataPacket` is not a key. It's the type/class/instanceof of `{id: 1, name: 'test'}`. This is how Google Chrome, Firefox and now node.js display types in `console.log()` – slebetman May 24 '22 at 04:46
  • @slebetman could you clarify on this? I tried with both with POJO and classes on the developer console of Chrome, but I don't see anything similar. – Mario Vernari May 24 '22 at 05:54
  • For example, when you do `document.getElementsByClassName('foo')` Google Chrome will print `HTMLCollection []` in the console. We all know this is invalid javascript syntax. It is just `[]` - an empty array-like object (HTMLCollection). The `HTMLCollection` has no meaning in javascript syntax but Google Chrome is just trying to be friendly and tell us that the `[]` is an `HTMLCollection` and not an array. That's what's going on here. The value of the variable is just `[{},{},{},{}]` but node.js wants to be helpful and tell us what type of object is in that array – slebetman May 24 '22 at 07:04
  • ... so it prints `[RowDataPacket {}, RowDataPacket {}, RowDataPacket {}]` when actually the value is `[{},{},{}]` – slebetman May 24 '22 at 07:05