我不知道这里发生了什么。我的应用程序在开发中运行良好,但是当我推送到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");
});
[使用邮递员向localhost:3000/test
发出GET请求可以正常工作..但不适用于myapp.herokuapp.com/test
。这是怎么回事?
我在nuxt.config.js文件中看不到您的服务器中间件设置。如果没有,那很有可能就是为什么它不起作用。你包括那些吗?这是有关如何使用nuxt设置服务器中间件的部分文档副本。如果您为nuxt编写自定义中间件,请确保将其放在api目录中,而不要放在中间件目录中,因为如果我没有记错的话,中间件目录仅与客户端上的路由器中间件相关。
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服务器中间件文档](https://nuxtjs.org/api/configuration-servermiddleware/)的链接,提供了更多信息。