Mik*_*e K 6 heroku node.js express vue.js nuxt.js
我不知道这里发生了什么。我的应用程序在开发中运行良好,但是当我推送到 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();
Run Code Online (Sandbox Code Playgroud)
和我的 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
}
};
Run Code Online (Sandbox Code Playgroud)
如您所见,我有一条测试路线:
app.get("/test", (req, res) => {
return res.send("Received");
});
Run Code Online (Sandbox Code Playgroud)
使用 Postman 发出 GET 请求可以localhost:3000/test正常工作.. 但它不适用于myapp.herokuapp.com/test. 这里发生了什么?
我在 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') }
]
}
Run Code Online (Sandbox Code Playgroud)
这是nuxt 服务器中间件文档的链接,可提供更多信息。
我觉得因为您在快递服务器中定义了路线,所以您不需要执行上述步骤,但尝试一下也没什么坏处。也许甚至可以尝试将路由移动到 api 目录中,就像他们在文档中所做的那样。只是为了确保 nuxt 正确注册路由。
我不确定,但我认为 nuxt 可能会将 api 路由注册为 url/api/yourRoute。也许可以尝试 myapp.herokuapp.com/api/test。这就是我能想到的所有可能的问题,除非项目的部署方式存在问题。不幸的是,我还没有部署到heroku,所以我无法提供任何进一步的建议。
| 归档时间: |
|
| 查看次数: |
839 次 |
| 最近记录: |