D
D
Dubolom Unicellular2020-07-10 20:40:56
Express.js
Dubolom Unicellular, 2020-07-10 20:40:56

Why doesn't get route with :id work in Express?

Why doesn't get route with :id work for me at all?
After some time, I realized that the error lies on the server, although I'm not completely sure.

Files:

Here get doesn't work at all, even console.log() does nothing. link.routes.js

const {Router} = require("express");
const auth = require("../middleware/auth.middleware");
const config = require("config");
const shortid = require("shortid");
const Link = require("../models/Link");

const router = new Router();

router.post("/generate", auth, async (req, res) => {
  try {
    const baseUrl = config.get("baseUrl");
    const {from} = req.body;

    const code = shortid.generate();

    const existing = await Link.findOne({ from });

    if(existing){
      return res.json({ link: existing })
    }

    const to = baseUrl + "/t/" + code;

    const link = new Link({
      code, to, from, owner: req.user.userId
    });

    await link.save();

    res.status(200).json({ link });

  } catch (e) {
    res.status(500).json({ error: "Что-то пошло не так, попробуйте снова" });
  }
});
router.get("/", auth, async (req, res) => {
  try {
    const links = await Link.find({ owner: req.userId });
    res.json(links);

  } catch (e) {
    res.status(500).json({ error: "Что-то пошло не так, попробуйте снова" });
  }
});
router.get("/:id", auth, async (req, res) => {
  try {
    const link = await Link.findById(req.params.id);
    res.json(link);

  } catch (e) {
    res.status(500).json({ error: "Что-то пошло не так, попробуйте снова" });
  }
});

module.exports = router;


app.js

const express = require("express");
const config = require("config");
const mongoose = require("mongoose");

const app = express();

app.use(express.json({extended: true}));

app.use("/api/auth", require("./routes/auth.routes"));
app.use("/api/link", require("./routes/link.routes"));

const PORT = config.get("port") | 5000;

async function start(){
  try {
    await mongoose.connect(config.get("mongoUri"), {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true
    });
    app.listen(PORT, () => console.log(`App has been started on ${PORT}!...`));
  } catch (e) {
    console.log("Server error", e.message);
    process.exit(1);
  }
}
start();


client/routes.js
import React from "react";
import {Switch, Route, Redirect} from "react-router-dom";
// pages
import {LinksPage} from "./pages/LinksPage";
import {CreatePage} from "./pages/CreatePage";
import {DetailPage} from "./pages/DetailPage";
import {AuthPage} from "./pages/AuthPage";

export const useRoutes = (isAuth) => {
  if(isAuth){
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id"> // тут :id тоже поставлен
          <DetailPage />
        </Route>
        <Redirect to="/create" />
      </Switch>
    )
  }

  return (
    <Switch>
      <Route path="/" exact>
        <AuthPage />
      </Route>
      <Redirect to="/" />
    </Switch>
  )
}


client/pages/DetailPage.js

import React, {useState, useEffect, useCallback, useContext} from "react";
import {useParams} from "react-router-dom";
import {useHttp} from "../hooks/http.hook";
import {AuthContext} from "../context/auth.context";
// components
import {Loader} from "../components/Loader";
import {LinkCard} from "../components/LinkCard";

export const DetailPage = () => {
  const {request, loading} = useHttp();
  const {token} = useContext(AuthContext);
  const [link, setLink] = useState(null);
  const linkId = useParams().id;

  const getLink = useCallback(async () => {
    try {
      const fetched = await request(`/api/link/${linkId}`, "GET", null, {
        Auth: `Bearer ${token}`
      });
      // все что пишу после request функции, не работает
      setLink(fetched);
    } catch (e) {}
  }, [request, token, linkId]);

  useEffect(() => {
    getLink();
  }, [getLink]);

  if(loading){
    return <Loader />
  }

  return (
    <>
      { !loading && link && <LinkCard link={link} /> }
    </>
  )
};


The request function simply does a fetch() with the parameters specified in the function.

What to do?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question