Any recommendations from this awesome community? I am not able to JSON.parse a response from a sub-worker, but if I use the response as a direct string to test, it works. I confirmed the returned json is valid in a JSON lint tester online.
Error message:
"MSG: \"[object Object]\" is not valid JSON, Stack:SyntaxError: \"[object Object]\" is not valid JSON\n at JSON.parse ()\n at d1-beta-facade.entry.js:1306:21\n at async d1-beta-facade.entry.js:1270:7\n at async d1-beta-facade.entry.js:1210:50"
Worker I am calling to validate a JWT token which returns a JSON.stringified object:
import jwt from '@tsndr/cloudflare-worker-jwt'
export default {
async fetch(request, env) {
const tokenField = request.headers.get('authorization')
// Remove the "bearer" label
const token = tokenField.substring(6).trim();
try {
// NOTE: Validate also checks the timestamp TTL
const isValid = await jwt.verify(token, env.JWT_TOKEN_KEY, { algorithm: 'HS256' })
if (!isValid) {
return new Response('Invalid Java Web Token (JWT) 1.', { status: 403 });
}
else {
const { payload } = jwt.decode(token)
// return new Response(JSON.stringify(payload), { status: 200 })
const json = JSON.stringify(payload, null, 2);
return new Response(json, {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
})
}
} catch (e) {
return new Response('Invalid Java Web Token (JWT) 2.', { status: 403 });
}
},
};
The worker calling the above sub-worker:
import { Hono } from 'hono';
import { cors } from 'hono/cors';
const app = new Hono()
app.use('/*', cors());
interface UserJwt {
sub: string;
name: string;
email: string;
roles: string;
exp: number;
iat: number;
}
app.post('/', async c => {
try {
// This fails
const results = await c.env.authsvc.fetch(c.req.clone())
// It returns this: '{"sub":"[email protected]","name":"[email protected]","email":"[email protected]","roles":"user tester","exp":1672242676,"iat":1672235476}'
let user: UserJwt = JSON.parse(results);
return c.json(user.name);
// This works
// let user: UserJwt = JSON.parse('{"sub":"[email protected]","name":"[email protected]","email":"[email protected]","roles":"user tester","exp":1672242676,"iat":1672235476}');
// return c.json(user.name);
} catch (exception: any) {
return c.json("MSG: " + exception.message + ", Stack:" + exception.stack);
}
});
export default app;
Thanks for any pointers.