我不知道这里发生了什么。我的应用程序在开发中运行良好,但是当我尝试使用Heroku时,每当我尝试使用Postman(或Axios)访问任何路线时,它都会引发404错误。我在这里做什么错了?
这是我的index.js:
const express = require("express");
const consola = require("consola");
const { log } = console;
const { Nuxt, Builder } = require("nuxt");
const app = express();
// Import and Set Nuxt.js options
let config = require("../nuxt.config.js");
// Use routes
app.use("/api/search", require("./api/search"));
app.get("/test", (req, res) => {
return res.send("Received");
});
config.dev = process.env.NODE_ENV !== "production";
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config);
const { host, port } = nuxt.options.server;
const PORT = process.env.PORT || port;
const HOST = process.env.PORT ? "myapp.heroku.com" : host;
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt);
await builder.build();
} else {
await nuxt.ready();
}
// Give nuxt middleware to express
app.use(nuxt.render);
// Listen the server
app.listen(PORT, HOST);
consola.ready({
message: `Server listening on http://${HOST}:${PORT}`,
badge: true
});
}
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
start();
还有我的nuxt.config.js
const pkg = require("./package");
module.exports = {
mode: "universal",
head: {
title: "My app",
meta: [
{ ...
},
{ ...
},
{ ...
},
{ ...
}
],
link: [
{ ...
},
{ ...
},
{ ...
}
],
script: [ ...
]
},
/*
** Nuxt.js modules
*/
modules: [
[
"@nuxtjs/axios",
{
baseURL: "https://myapp.herokuapp.com"
}
],
"bootstrap-vue/nuxt",
],
router: {
scrollBehavior: async (to, from, savedPosition) => {
if (savedPosition) {
return savedPosition;
}
const findEl = async (hash, x) => {
return ( ...
);
};
if (to.hash) {
let el = await findEl(to.hash);
if (el) { ...
}
}
return { ... };
}
},
/*
** Build configuration
*/
build: {
optimization: { ...
},
analyze: false
}
};
如您所见,我有一条测试路线:
app.get("/test", (req, res) => {
return res.send("Received");
});
使用Postman向localhost:3000/test
发出GET请求可以正常工作..但不适用于myapp.herokuapp.com/test
。这是怎么回事?
答案 0 :(得分:0)
我在nuxt.config.js文件中看不到您的服务器中间件设置。您添加了吗?如果没有,那很有可能就是为什么它不起作用。这是有关如何使用nuxt设置服务器中间件的部分文档副本。
import serveStatic from 'serve-static'
export default {
serverMiddleware: [
// Will register redirect-ssl npm package
'redirect-ssl',
// Will register file from project api directory to handle /api/* requires
{ path: '/api', handler: '~/api/index.js' },
// We can create custom instances too
{ path: '/static2', handler: serveStatic(__dirname + '/static2') }
]
}
这是指向nuxt server middleware docs的链接,以获取更多信息。
我感觉是因为您在快递服务器中定义了路由,因此无需采取上述步骤,但尝试也不会受到伤害。甚至可以尝试像将文档中那样将路由移动到api目录中。只是为了确保nuxt正确注册了路由。
我不确定,但我认为nuxt可能会将api路由注册为url / api / yourRoute。也许尝试myapp.herokuapp.com/api/test。除非项目部署方式存在问题,否则这就是我能想到的所有可能问题。不幸的是,我还没有部署到heroku,所以我真的无法提供任何进一步的建议。
答案 1 :(得分:0)
为我解决的问题是将Procfile中的命令从nuxt start
更改为npm run start
,否则没有服务器端代码在运行。