Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

tRPC query request won't pass my query parameter

Hi when I send request to http://localhost:5000/trpc/test?val=teststring by using below minimal reproducible example, it returns message: "Invalid input: undefined" because as it says, the val really is undefined. What am I doing wrong? I tried to follow the tRPC docs for getting started.

When I sent request to http://localhost:5000/trpc/test?input=teststring, it says, "Unexpected token e in JSON at position 1" in the response. Is sending request like this to tRPC invalid?

index.ts

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import express from "express";
import { initTRPC } from "@trpc/server";
import * as trpcExpress from "@trpc/server/adapters/express";

const t = initTRPC.create();
const router = t.router;

export const appRouter = router({
  test: t.procedure
    .input((val: unknown) => {
      console.log({val})
      if (typeof val === 'string') return val;
      throw new Error(`Invalid input: ${typeof val}`);
    })
    .query((req) => {
      const input = req.input;
      return { msg: `You requested: ${input}`};
    }),
});

export type AppRouter = typeof appRouter;

const app = express();
const port = 5000;

app.get("/", (req, res) => {
  res.send("Hello from api-server");
});

app.use(
  "/trpc",
  trpcExpress.createExpressMiddleware({
    router: appRouter,
  })
);
app.listen(port, () => {
  console.log(`api-server listening at http://localhost:${port}`);
});

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

package.json

{
  "name": "api-server",
  "version": "1.0.0",
  "license": "MIT",
  "scripts": {
    "start": "ts-node index.ts"
  },
  "dependencies": {
    "@trpc/server": "^10.14.0",
    "express": "^4.17.1",
    "zod": "^3.21.0"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "ts-node": "^10.4.0",
    "typescript": "^4.4.4"
  }
}

>Solution :

Trpc expects you to pass params in a specific way. You can read their documentation here https://trpc.io/docs/rpc

Here is the example they use myQuery?input=${encodeURIComponent(JSON.stringify(input))}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading