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;
CodePudding user response:
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?
CodePudding user response:
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' }
]