我正在使用angular 8,并希望在我的应用程序中支持ssr。
当我通过server.ts和在node.js中开发的api从angular应用程序内部调用api时,SSR无法处理此api请求。
如果我从外部调用相同的api则工作正常。
Server.ts
import "zone.js/dist/zone-node";
import * as express from "express";
import { join } from "path";
import bodyParser from "body-parser";
import { ApiRoute } from "./routes/api-route";
const apiRoute: ApiRoute = new ApiRoute();
var fs = require("fs");
var https = require("https");
var cors = require("cors");
var privateKey = fs.readFileSync("./ssl/private.key", "utf8");
var certificate = fs.readFileSync("./ssl/certifcate.crt", "utf8");
var cabundle = fs.readFileSync("./ssl/bundle.ca-bundle", "utf8");
var credentials = { key: privateKey, cert: certificate, ca: cabundle };
// Express server
const app = express();
app.use(cors());
var httpsServer = https.createServer(credentials, app);
const PORT = process.env.PORT || 443;
const DIST_FOLDER = join(process.cwd(), "dist/browser");
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {
AppServerModuleNgFactory,
LAZY_MODULE_MAP,
ngExpressEngine,
provideModuleMap
} = require("./dist/server/main");
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine(
"html",
ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [provideModuleMap(LAZY_MODULE_MAP)]
})
);
// useing bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "html");
app.set("views", DIST_FOLDER);
// Example Express Rest API endpoints
apiRoute.apiRoute(app);
app.get("/api/**", (req, res) => {});
// Serve static files from /browser
app.get(
"*.*",
express.static(DIST_FOLDER, {
maxAge: "1y"
})
);
// APIs
apiRoute.apiRoute(app);
// All regular routes use the Universal engine
app.get("/*", (req, res) => {
res.render("index", { req });
});
// Start up the Node server
httpsServer.listen(PORT);
apiRoute.ts
export class ApiRoute {
public apiRoute(app): void {
// api for get header coupon
app.route("/api/getheadercoupon").get(function(req, res) {
var responseData = {};
Coupon.getHeaderCoupon(function(coupon) {
console.log(coupon);
if (coupon.errno) {
responseData["message"] = "Some error occur";
responseData["response"] = 0;
responseData["error"] = coupon.code;
return res.json(responseData);
} else {
if (coupon.length > 0) {
responseData["message"] = "Success";
responseData["response"] = 1;
responseData["data"] = coupon[0];
return res.json(responseData);
} else {
responseData["message"] = "No record found!";
responseData["response"] = 0;
return res.json(responseData);
}
}
});
});
}
}
请帮助我。 谢谢。