Transform Express.js api route into Nexjs api

Issue

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?

Solution

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

Answered By – Lunatix01

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published