【发布时间】:2020-05-01 12:22:00
【问题描述】:
我在基于Koa template 的后端使用 Koa 作为 API / 控制器在通用模式下运行 Nuxt。我正在部署到 Heroku。 API 在本地工作正常,但在生产中返回 404。我认为该应用程序在部署时作为 SPA 运行,其他一切运行良好。
这是我的服务器/index.js
const Koa = require('koa')
const consola = require('consola')
const Router = require('koa-router');
const { Nuxt, Builder } = require('nuxt')
const api = require('./api');
console.log('server works'); // ------> This line gets ignored by the Heroku console
const app = new Koa()
const router = new Router();
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'
router.use('/api', api.routes(), api.allowedMethods());
app.use(router.routes());
async function start () {
// Instantiate nuxt.js
const nuxt = new Nuxt(config)
const {
host = process.env.HOST || '127.0.0.1',
port = process.env.PORT || 3000
} = nuxt.options.server
// Build in development
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
app.use((ctx) => {
ctx.status = 200
ctx.respond = false // Bypass Koa's built-in response handling
ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
nuxt.render(ctx.req, ctx.res)
})
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`, // ------> Neither this line appears in Heroku console
badge: true
})
}
start()
过程文件
web: nuxt start
来自 package.json 的脚本
"scripts": {
"dev": "cross-env HOST=192.168.1.65 NODE_ENV=development nodemon server/index.js --watch server ",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate",
"test": "ava",
"test:unit": "cross-env TEST=unit ava --config unit.config.js",
"test:e2e": "cross-env TEST=e2e ava --config e2e.config.js",
"heroku-postbuild": "nuxt build"
}
我想我在阅读 all these 部署文档并没有看到明显的内容后得到了 nu(x)ts。
谢谢。
【问题讨论】:
-
您是否在 Heroku 上使用
0.0.0.0值从Settings > Config Vars创建了HOST环境变量? -
当然,我做到了,我完全按照文档进行操作。前端工作正常。问题出在后端。
-
您可以添加您的
package.json文件
标签: node.js heroku package.json koa nuxt.js