Node.js 使用Nuxt部署到Heroku时获得API路由的404
我不知道这里发生了什么。我的应用程序在开发过程中运行良好,但当我推到Heroku时,每当我尝试使用Postman(或Axios)访问任何路由时,它都会抛出404个错误。我做错了什么 这是我的index.js:Node.js 使用Nuxt部署到Heroku时获得API路由的404,node.js,express,vue.js,heroku,nuxt.js,Node.js,Express,Vue.js,Heroku,Nuxt.js,我不知道这里发生了什么。我的应用程序在开发过程中运行良好,但当我推到Heroku时,每当我尝试使用Postman(或Axios)访问任何路由时,它都会抛出404个错误。我做错了什么 这是我的index.js: const express = require("express"); const consola = require("consola"); const { log } = console; const { Nuxt, Builder } = require("nuxt"); con
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();
我的numxt.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设置服务器中间件的部分文档的副本
从“服务静态”导入serveStatic
导出默认值{
服务器中间件:[
//将注册重定向ssl npm包
“重定向ssl”,
//将从project api目录注册文件以处理/api/*所需
{path:'/api',handler:'~/api/index.js'},
//我们也可以创建自定义实例
{path:'/static2',处理程序:serveStatic(uu dirname+'/static2')}
]
}
这里有一个链接到fore更多信息
我觉得,因为您在express服务器中定义了路由,所以不需要执行上述步骤,但尝试也无妨。甚至可以像文档中那样尝试将路由移动到api目录中。只是为了确保nuxt正确注册路由
我不确定,但我认为nuxt可能会将api路由注册为url/api/yourRoute。也许可以试试myapp.herokuapp.com/api/test。这就是我能想到的所有可能的问题,除非项目的部署方式有问题。不幸的是,我没有部署到heroku,因此我无法提供任何进一步的建议。为我解决这一问题的方法是将Procfile中的命令从
nuxt start
更改为npm run start
,否则没有运行任何服务器端代码。您解决了这个问题吗?我也遇到同样的问题