Code below.
The following error is console logged:
{status: 'PARSING_ERROR', originalStatus: 200, data: '<!DOCTYPE html>\n<html lang="en">\n <head>\n <met…uild` or `yarn build`.\n -->\n </body>\n</html>\n', error: `SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON`}
data: "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link rel=\"icon\" href=\"/favicon.ico\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta name=\"theme-color\" content=\"#000000\" />\n <meta\n name=\"description\"\n content=\"Web site created using create-react-app\"\n />\n <link rel=\"apple-touch-icon\" href=\"/logo192.png\" />\n <!--\n manifest.json provides metadata used when your web app is installed on a\n user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n -->\n <link rel=\"manifest\" href=\"/manifest.json\" />\n <!--\n Notice the use of in the tags above.\n It will be replaced with the URL of the `public` folder during the build.\n Only files inside the `public` folder can be referenced from the HTML.\n\n Unlike \"/favicon.ico\" or \"favicon.ico\", \"/favicon.ico\" will\n work correctly both with client-side routing and a non-root public URL.\n Learn how to configure a non-root public URL by running `npm run build`.\n -->\n <title>React App</title>\n <script defer src=\"/static/js/bundle.js\"></script></head>\n <body>\n <noscript>You need to enable JavaScript to run this app.</noscript>\n <div id=\"root\"></div>\n <!--\n This HTML file is a template.\n If you open it directly in the browser, you will see an empty page.\n\n You can add webfonts, meta tags, or analytics to this file.\n The build step will place the bundled scripts into the <body> tag.\n\n To begin the development, run `npm start` or `yarn start`.\n To create a production bundle, use `npm run build` or `yarn build`.\n -->\n </body>\n</html>\n"
error: "SyntaxError: Unexpected token '<', \"<!DOCTYPE \"... is not valid JSON"
originalStatus: 200
status: "PARSING_ERROR"
[[Prototype]]: Object
when I console log:
console.log(useGetKpisQuery());
some investigation revealed in the network tab of dev tools that RTK query seems to be trying to query http://localhost: instead of the expected endpoint.
state/api.ts
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: import.meta.env.VITE_BASE_URL }),
reducerPath: "main",
tagTypes: ["Kpis"],
endpoints: (build) => ({
getKpis: build.query<void, void>({
query: () => "kpi/kpis/",
providesTags: ["Kpis"],
}),
}),
});
export const { useGetKpisQuery } = api;
store in my main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "@/App.tsx";
import "./index.css";
import { Provider } from "react-redux";
import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/dist/query";
import { api } from "@/state/api";
const store = configureStore({
reducer: { [api.reducerPath]: api.reducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(api.middleware),
});
setupListeners(store.dispatch);
ReactDOM.createRoot(document.getElementById("root")!).render(
<Provider store={store}>
<App />
</Provider>
);
routes/kpi.js
import express from "express";
import KPI from "../models/KPI.js";
import { kpis } from "../data/data.js";
const router = express.Router();
router.get("/kpis", async (req, res) => {
try {
const kpis = await KPI.find();
res.status(200).json(kpis);
} catch (error) {
res.status(404).json({ message: error.message });
}
});
export default router;
where I'm trying to access that data at the endpoint: ./Row1.tsx
import DashboardBox from "@/components/DashboardBox";
import { useGetKpisQuery } from "@/state/api";
type Props = {};
const Row1 = (props: Props) => {
const { data } = useGetKpisQuery();
console.log(useGetKpisQuery());
return (
<>
<DashboardBox gridArea="a"></DashboardBox>
<DashboardBox gridArea="b"></DashboardBox>
<DashboardBox gridArea="c"></DashboardBox>
</>
);
};
export default Row1;
Also server config:
import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import helmet from "helmet";
import morgan from "morgan";
import kpiRoutes from "./routes/kpi.js";
import KPI from "./models/KPI.js";
import { kpis } from "./data/data.js";
dotenv.config();
const app = express();
app.use(express.json());
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use(morgan("common"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
// Routes
app.use("/kpi", kpiRoutes);
const PORT = process.env.PORT || 9000;
Any help appreciated!
- checked and matched all the imports/exports.
- tried encodeURIComponent() on my api query.
- thought it might be a problem with a missing bodyparser call but it's all there
Do you use react-router for you app? I've encounter the same issue. In my case, the react-router url is the same with the api address. renaming either one of them fix my issue.