I am using Express as my backend and for some reason my GET request is not working to query a Postgres database. I am pretty sure I am supposed to use GET request to query the database but can't seem to get it to work. I get the error below.
SyntaxError: Unexpected token < in JSON at position 0
Here is the code for the GET request
const express = require("express");
const router = express.Router();
const pool = require("./db");
router.get("/", async (req, res, next) => {
pool.connect((err, client, done) => {
if (err) throw err;
client.query("SELECT * FROM pledges", (err, ress) => {
done();
if (err) {
console.log(err.stack);
} else {
console.log(ress.rows[0]);
res.json(ress.rows.reverse());
}
});
});
});
However, if I change it to a POST request, I get the correct query and returns the whole table. What am I doing wrong?
const express = require("express");
const router = express.Router();
const pool = require("./db");
router.post("/", async (req, res, next) => {
pool.connect((err, client, done) => {
if (err) throw err;
client.query("SELECT * FROM pledges", (err, ress) => {
done();
if (err) {
console.log(err.stack);
} else {
console.log(ress.rows[0]);
res.json(ress.rows.reverse());
}
});
});
});
Here is my FETCH
useEffect(() => {
fetch("/pledges")
.then((response) => response.json())
.then((data) => {
console.log(data);
setPledges(data);
})
.catch((error) => {});
}, []);
Fetch with POST request
useEffect(() => {
fetch("/pledges", {
method: "POST",
})
.then((response) => response.json())
.then((data) => {
setPledges(data);
})
.catch((error) => {});
}, []);
CodePudding user response:
Likely the server is returning something that is not JSON, something with a "<" in it, like XML or HTML. Try setting the content header appropriately.
fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})