Я разработал приложение реагирования, используя next.js.
Теперь я хочу развернуть его в Google Cloud App Engine.
Приложение включает в себя интерфейс реакции и mock-API (включая mock.db) для временного хранения данных во времяразвитие.
Проблема заключается в следующем: Первый открытый мной экземпляр работал правильно. Как только я открыл его в другом браузере, было запущено только приложение реакции, но API там не было (в результате приложение React показывало только элементы управления и никаких данных). Сервер API доступен через localhost: 3033
То же самое относится и к моему коллеге, который пытался открыть его, видя только белизну.
Я не настроил ничего дополнительного в Google Cloud App Engine, простов основном ваниль.
Есть ли в этом что-то, когда App Engine раскручивает дополнительные экземпляры? Я не могу понять, что может вызвать эту проблему.
package.json
"prestart:api": "node createMockDb.js",
"start:api": "node apiServer.js",
"dev": "node server.js",
"build": "next build",
"start": "cross-env NODE_ENV=production node server.js & node createMockDB.js & node apiServer.js"
server.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 8080;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("/products/overview", (req, res) => {
return app.render(req, res, "/products/overview", req.query);
});
server.get("/products/roadmap", (req, res) => {
return app.render(req, res, "/products/roadmap", req.query);
});
server.get("/strategy/goals", (req, res) => {
return app.render(req, res, "/strategy/goals", req.query);
});
server.get("/strategy/metrics", (req, res) => {
return app.render(req, res, "/strategy/metrics", req.query);
});
/* server.get("/posts/:id", (req, res) => {
return app.render(req, res, "/posts", { id: req.params.id });
}); */
server.all("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
apiServer.js
/* eslint-disable func-names */
/* eslint-disable no-console */
const jsonServer = require("json-server");
const server = jsonServer.create();
const path = require("path");
const router = jsonServer.router(path.join(__dirname, "server/db.json"));
const middlewares = jsonServer.defaults({
static: "node_modules/json-server/dist"
});
server.use(middlewares);
server.use(jsonServer.bodyParser);
server.use(function(req, res, next) {
setTimeout(next, 0);
});
function createSlug(value) {
return value
.replace(/[^a-z0-9_]+/gi, "-")
.replace(/^-|-$/g, "")
.toLowerCase();
}
function validateProduct(product) {
if (!product.title) return "Title is required.";
if (!product.tagline) return "Tagline is required.";
if (!product.description) return "Description is required.";
return "";
}
server.use((req, res, next) => {
if (req.method === "POST") {
req.body.createdAt = Date.now();
}
next();
});
server.post("/products/", function(req, res, next) {
const error = validateProduct(req.body);
if (error) {
res.status(400).send(error);
} else {
req.body.slug = createSlug(req.body.title);
next();
}
});
server.use(router);
const port = 3033;
server.listen(port, () => {
console.log(`JSON Server is running on port ${port}`);
});