Home > OS >  How to use Incomplete paths in app get (Express js)
How to use Incomplete paths in app get (Express js)

Time:07-16

Hay everyone, I wrote a simple express js code that has six different routes:
"/,
"/routes/show-stocks",
"/routes/show-stocks/btc",
"/routes/show-stocks/eth",
"/routes/show-stocks/ada",
"/routes/show-stocks/doge".
I used app.use to be able to use "/show-stocks" as the path insted the full one: "/routes/show-stocks
this is how I did it: (app.js)

const express = require("express");

const app = express();
const port = 4000;

app.get("/", (req, res) => res.send("Testing on Mac"));

const get_stocks = require("./routes/show-stocks");
app.use("/show-stocks", get_stocks);

app.listen(port, () => console.log("Testing on Mac on port: "   port));

So if the user want to reach /routes/show-stocks/btc he only need to type /show-stocks/btc
This is my "/routes/show-stocks.js":

import express from "express";
const router = express.Router();

router.get("/btc", (req, res) => {
  // ...
});

router.get("/ada", (req, res) => {
  // ...
});

router.get("/eth", (req, res) => {
  // ...
});

router.get("/doge", (req, res) => {
  // ...
});

module.exports = router;

But now I need to use import instead of require in my app.js file. My problem is that I do not know how I can implement this code with "import" instead, and preserve the same logic.
Can anyone help me do that?

CodePudding user response:

This seems to work:

notice the import express from "express"; and import get_stocks from "./routes/show-stocks.js";

import express from "express";

const app = express();
const port = 4000;

app.get("/", (req, res) => res.send("Testing on Mac"));

import get_stocks from "./routes/show-stocks.js";
app.use("/show-stocks", get_stocks);

app.listen(port, () => console.log("Testing on Mac on port: "   port));

You'll need to add the "type": "module" to your package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  }
}

My quick improvised route file: Notice the export default router at the bottom.

import express from "express";
const router = express.Router();

router.get("/btc", (req, res) => {
  res.send("btc");
});

router.get("/ada", (req, res) => {
  res.send("ada");
});

router.get("/eth", (req, res) => {
  res.send("eth");
});

router.get("/doge", (req, res) => {
  res.send("doge");
});

export default router;
  • Related