Следующие js и Express как средние. Как установить localhost: 3000 / newpage и localhost: 3000 / newpage / как одни и те же маршруты - PullRequest
1 голос
/ 17 июня 2020

Я новичок в express и далее и пытался установить localhost: 3000 / newpage и localhost: 3000 / newpage / в качестве одного и того же маршрута, однако, когда я добавляю '/' в конце, он показывает ошибка 404.

Я использую "next-routes" для динамической c маршрутизации и создал маршруты. js файл, который выглядит следующим образом:

const nextRoutes = require("next-routes");
const routes = (module.exports = nextRoutes());

routes.add("index", "/");
routes.add("newpage", "/newpage/:slug"); //with body parser this doesnt work

и мой сервер. js файл выглядит так:

const express = require("express");
const next = require("next");
const routes = require("./routes");
const dev = process.env.NODE_ENV !== "production";
const port = process.env.PORT || 3000;
const app = next({ dev });
const handle = app.getRequestHandler();
const bodyParser = require("body-parser");
const handler = routes.getRequestHandler(app);
app
  .prepare()
  .then(() => {
    const server = express();
    server.use(bodyParser.json()); //with this dynamic routes dont work
    server.use (handler); //with this dynamic routes work but / url show 404

    server.get("*", (req, res) => {
      server.use(handler);
      if (req.url.endsWith("/")) {
        req.url = req.url.slice(0, -1); // works only when using body parser
      }
      return handle(req, res);
    });

    server.listen(port, (err) => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });



Ответы [ 2 ]

1 голос
/ 17 июня 2020

Вы можете изменить URL-адрес, который вы получите, прежде чем передавать его обработчику Next.

const next = require('next');
const express = require('express');
const routes = require('./routes');
const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({dev});
const handle = app.getRequestHandler();
// const handler = routes.getRequestHandler(app); // redundant line

app.prepare().then(() => {
  const server = express();
  // server.use(handler); // <-- this line is redundant since you need only one handle!
  server.get('*', (req, res) => {
    if (req.url.endsWith('/')) {
      req.url = req.url.slice(0, -1); // remove the last slash
    }
    return handle(req, res);
  });
  server.listen(port, (err) => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

Рабочий пример: https://codesandbox.io/s/express-nextjs-react-c47y8?file= / src / index. js

Перейдите в / form или / form /

0 голосов
/ 17 июня 2020

Мне пришлось установить пакет body-parser, а затем использовать body-parser. Я также изменил структуру папок, так что мне не нужно было импортировать маршруты. Последний код в server. js выглядит так:

const express = require("express");
const next = require("next");

const dev = process.env.NODE_ENV !== "production";
const port = process.env.PORT || 3000;
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();

    server.get("*", (req, res) => {
      if (req.url.endsWith("/")) {
        req.url = req.url.slice(0, -1); // remove the last slash
      }

      return handle(req, res);
    });

    server.listen(port, (err) => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

...