javascript 下一个路由server.js失败:类型错误:routes.getRequestHandler不是函数

hrirmatl  于 2023-01-24  发布在  Java
关注(0)|答案(5)|浏览(136)

我在server.js中遇到一个错误。我的脚本如下所示:

const { createServer } = require('http');
const next = require('next');
const routes = require('./routes');

const app = next ({
  dev: process.env.NODE_ENV !== 'production'
});

const handler = routes.getRequestHandler(app);

app.prepare().then( () =>{
  createServer(handler).listen(3000, (err) => {
    if (err) throw err;
    console.log('Ready on localhost:3000');
  });
});

它几乎是直接从next-routes文档中复制出来的。这是我运行〉npm run dev时得到的结果

C:\Users\zangezi39\kickstart\server.js:9

const handler = routes.getRequestHandler(app);
                ^                       
TypeError: routes.getRequestHandler is not a function

    at Object.<anonymous> (C:\Users\zangezi39\kickstart\server.js:9:24)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! kickstart@1.0.0 dev: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the kickstart@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
58wvjzkj

58wvjzkj1#

必须更改routes.js脚本
请检查const routes = require('next-routes');是否更改为const routes = require('next-routes')();

5t7ly7z5

5t7ly7z52#

不是那样,看看这个

const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });

const handler = app.getRequestHandler();
rbpvctlc

rbpvctlc3#

您只是在该行的末尾忘记了一个,
下面是适合我的代码:

const {createServer} = require('http');
    const next = require('next');

    const app = next({
     dev: process.env.NODE_ENV !== 'production',
    });

    const routes = require('./routes');
    const handler = routes.getRequestHandler(app);

    app.prepare().then(() => {
      createServer(handler).listen(3000, (err) => {
       if (err) throw err;
         console.log('Ready on localhost: 3000');
      });
    });
lb3vh1jj

lb3vh1jj4#

我有同样的错误,当routes.jsserver.js处于同一级别时,我修复了该错误,此外,您还应确保routes.js如下所示

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

许多程序员忘记在最后导出routes模块,因此您应该在routes.js中包含'module.exports = routes'。另外,转到package.json文件并检查是否安装了nextnext-routes模块

eulz3vhy

eulz3vhy5#

确保在routes.js文件中的const routes = require(“next-routes”“'()'末尾添加'()'

相关问题