Yêu cầu Apr 20th, 2021 1:54 a.m. 251 0 1
  • 251 0 1
+1

NextJS chạy bản producttion không thể chạy node server

Chia sẻ
  • 251 0 1

Chào mọi người, hiện tại em đang làm dự án với NextJs. Khi em chạy yarn dev thì gọi được đến server.js, nhưng khi chạy yarn start cho bản build thì không thể gọi đến server.js được (chính xác là lỗi 404 ạ).
Mọi người có ai gặp trường hợp này hỗ trợ giúp em với ạ. Em tìm trên mạng thử nhiều cách rồi mà không được.
Một vài cách em thử như:

  • start_prod: SET NODE_ENV=production & node server.js (cái này thì nó lại chạy bản dev)
  • start_prod: NODE_ENV=production node server.js (cái này thì lại bị lỗi NODE_EVN)

Các file hiện tại của em nhưu sau ạ:
server.js

const Koa = require('koa')
const cors = require('@koa/cors')
const next = require('next')
const Router = require('koa-router')
const nextRoutes = require('./next-routes')

const port = parseInt(process.env.PORT, 10) || 3007
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = nextRoutes.getRequestHandler(app)
const koaBody = require('koa-body')

// const api = require('./koa/api');
const indexRoutes = require('./server/routes/index')

app.prepare()
    .then(() => {
        const server = new Koa()
        const router = new Router()

        router.get('*', async (context) => {
            await handle(context.req, context.res)
            context.respond = false
        })

        server.use(async (context, next) => {
            context.res.statusCode = 200
            await next()
        })

        // 미들웨어
        server.use(koaBody({ multipart: true }))
        server.use(
            cors({
                origin: '*',
                allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'OPTION', 'PATCH'],
                allowHeaders: ['Content-Type', 'Authorization'],
                exposeHeaders: ['Content-Length', 'Date', 'X-Request-Id'],
            })
        )
        // server.use(passport.initialize());

        // API
        server.use(indexRoutes.routes())

        server.use(router.routes())
        server.use(handle)
        server.listen(port, () => {
            console.info(`> Ready on http://localhost:${port}`)
        })
    })
    .catch((ex) => {
        // console.warn(ex)
        process.exit(1)
    })

package.json

"scripts": {
    "dev": "node server.js --exec",
    "build": "next build",
    "dev_build": "DEPLOY_ENV=dev next build",
    "prod_build": "next build",
    "prod_start": "node server.js",
    "start": "next start -p 3007"
  }

next.config.js

const withPlugins = require('next-compose-plugins')
const withOffline = require('next-offline')
const { GuessPlugin } = require('guess-webpack')
const withPWA = require('next-pwa')
require('dotenv').config()

const withEnv = {
    env: {
        DEPLOY_ENV: process.env.DEPLOY_ENV,
    },
}

module.exports = withPlugins([
    withCSS({
        webpack: function (config, { isServer }) {
            config.module.rules.push({
                test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        limit: 100000,
                        name: '[name].[ext]',
                    },
                },
            })
            return config
        },
    }),
    withOffline({
        workboxOpts: {
            swDest: '../public/sw/service-worker.js',
        },
        async rewrites() {
            return [
                {
                    source: '/service-worker.js',
                    destination: '/_next/static/service-worker.js',
                },
            ]
        },
    }),
    withPWA({
        pwa: {
            disable: process.env.DEPLOY_ENV !== 'production' ? true : false,
            dest: 'public/sw',
            scope: '/sw',
        },
    }),
    withEnv,
])
Avatar Nguyen Huy Cuong @cuong_nguyen
Apr 20th, 2021 3:38 a.m.

1 CÂU TRẢ LỜI


Đã trả lời Apr 20th, 2021 3:44 a.m.
Đã được chấp nhận
+1

bạn thử đọc lại phần này nhé, về cơ bản thì chạy prod cũng phải trỏ tới file server.js này, và config hàm next nhé, set dev = false thì sẽ chạy ở mode prod nhá, env nó ko nhận thì bạn dùng thử cross-env xem sao https://nextjs.org/docs/advanced-features/custom-server

const next = require('next')
const app = next({ dev: process.env.NODE_ENV !== 'production' })
Chia sẻ
Apr 20th, 2021 4:31 a.m.

Mình sửa lại như này thì chạy được server.js rồi ạ, cảm ơn bạn ^^

 "start": "cross-env NODE_ENV=production node server.js"
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí