Home > OS >  Transform Express.js api route into Nexjs api
Transform Express.js api route into Nexjs api

Time:08-30

I have this Express API route:

const router = require("express").Router();

router.get("/:jobId/:format", async (req, res) => {
  try {
    const { jobId, format } = req.params;

    if (format.toLowerCase() === "json") {
      const transcript = await req.asyncClient.getTranscriptObject(jobId);
      res.json(transcript);
      return;
    }

    if (format.toLowerCase() === "text") {
      const transcript = await req.asyncClient.getTranscriptText(jobId);
      res.send(transcript);
      return;
    }
    res.statusCode(500).send(`Invalid format ${format}`);
  } catch (error) {
    console.error(error.message);
    res.sendStatus(500);
  }
});

router.post("/", (req, res) => {
  req.io.emit(`transcript`, req.body);
  res.sendStatus(200);
});

module.exports = router;

and i want to convert it to an Nextjs API route. The part i don't understand the most is this line:

router.get("/:jobId/:format", async (req, res) => {...

How do i get /:jobId/:format in Nextjs?

CodePudding user response:

You can write something like that:

  • create a file inside /api called [...jobId].js

inside the file you can access /jobId/format like that

const { jobId } = req.query

it if format exists its returns something like that if someone send a request for /12345/json

{ "jobId": ["12345", "json"] }
  • Related