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
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"
}
}
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))}