-
When using the standalone server, it might be useful to handle CORS preflight requests. Currently the request just falls with a 405, Method Not Allowed. I'm proposing the addition of a |
Beta Was this translation helpful? Give feedback.
Answered by
KATT
Jul 12, 2021
Replies: 1 comment 1 reply
-
You can use the http handler straight-off. Example codeimport * as trpc from '@trpc/server';
import { z } from 'zod';
import http from 'http';
type Context = {};
export const appRouter = trpc.router<Context>().query('hello', {
input: z
.object({
name: z.string(),
})
.optional(),
resolve: ({ input }) => {
return {
text: `hello ${input?.name ?? 'world'}`,
};
},
});
export type AppRouter = typeof appRouter;
// create handler
const handler = trpc.createHttpHandler({
router: appRouter,
createContext() {
return {};
},
});
const server = http.createServer((req, res) => {
// do whatever you want here
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
handler(req, res);
});
server.listen(2022); |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
KATT
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use the http handler straight-off.
Example code