使用Nuxt部署到Heroku时获取404的API路由 [英] Getting a 404 for API routes when deploying to Heroku with Nuxt
问题描述
我不知道这是怎么回事.我的应用程序在开发中运行良好,但是当我推送到Heroku时,每当我尝试使用Postman(或Axios)访问任何路线时,它都会引发404错误.我在这里做什么错了?
I have no idea what is going on here. My app works just fine in development, but when I push to Heroku, it throws 404 errors whenever I try to access any routes with Postman (or with Axios). What am I doing wrong here?
这是我的index.js:
Here is my 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
}
};
如您所见,我有一条测试路线:
As you can see, I have a test route:
app.get("/test", (req, res) => {
return res.send("Received");
});
使用Postman向localhost:3000/test
发出GET请求可以正常工作..但是对myapp.herokuapp.com/test
无效.这是怎么回事?
Making a GET request using Postman to localhost:3000/test
works fine.. but it doesnt work for myapp.herokuapp.com/test
. What's going on here?
推荐答案
为我解决的问题是将Procfile中的命令从nuxt start
更改为npm run start
,否则没有服务器端代码在运行.
What solved this for me was changing the command in the Procfile from nuxt start
to npm run start
, otherwise none of the server side code was running.
这篇关于使用Nuxt部署到Heroku时获取404的API路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!