Home > Software engineering >  "message": "Cannot read properties of undefined (reading 'split')",
"message": "Cannot read properties of undefined (reading 'split')",

Time:08-02

"message": "Cannot read properties of undefined (reading 'split')", "stack": "TypeError: Cannot read properties of undefined (reading 'split') at /Users/dhruv/code/c0485f/src/api/posts.js:66:31 at Layer.handle [as handle_request] (/Users/dhruv/code/c0485f/node_modules/express/lib/router/layer.js:95:5) at next (/Users/dhruv/code/c0485f/node_modules/express/lib/router/route.js:144:13) at Route.dispatch (/Users/dhruv/code/c0485f/node_modules/express/lib/router/route.js:114:3) at Layer.handle [as handle_request] (/Users/dhruv/code/c0485f/node_modules/express/lib/router/layer.js:95:5) at /Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:284:15 at Function.process_params (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:346:12) at next (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:280:10) at Function.handle (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:175:3) at router (/Users/dhruv/code/c0485f/node_modules/express/lib/router/index.js:47:12)",

I am getting this error from the code attached below and while calling this API there is data in body "authorIds"

router.get('/', async (req, res, next) => {


 try {
    const { authorIds, sortBy = 'id', direction = 'asc' } = req.body;

//if access token is not verified then this statemnt will throw an error.
jwt.verify(req.headers['x-access-token'], process.env.SESSION_SECRET);

//finding all posts which all are associated with authorIds got from request.
const posts = await Post.findAll({
  order: [[sortBy, direction]],
  include: [
    {
      model: UserPost,
      required: true,
      attributes: [],
      where: {
        userId: authorIds.split(","),
      },
    },
  ],
});

//console.log(posts);
res.json({ posts });


} catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({ error: error.message });
    }
    next(error);
  }
});

CodePudding user response:

make sure you are sending the authorIds in request body and its value is valid and make sure you use express.json() middleware in your express app at the start so it can parse the body.

app.use(express.json());

and one more thing you are trying to read request body from a get request! get request cant carry a body, only query param and path param and headers are allowed.

turn it to a post request or send params in query or path.

  • Related