简体   繁体   中英

What is the quickest workaround to make Angular 4 routing work on a prod server?

I have spent 6 whole days for converting a HTML5 only app to Angular 4 routing app. Just to be able to use Angular 4 routing to make website more SEO friendly.

After developing it successfully I deployed it on the server just to realize the direct urls are resulting in 404 page. Example: http://abc .com/route

This same thing works fine on clicks of routerLinks. I have seen several blog posts about this issue but I am not able to decide on which will be the quickest solution for this. Can someone help me with it? I am not using Angular CLI, please note.

This is because all routes have to go to the the index.html and angular-router will do its routing from there. So get a node server up and running and redirect all request to index.html

this is how ur server might look like

import { json, urlencoded } from "body-parser";
import * as compression from "compression";
import * as express from "express";
import * as path from "path";


const app: express.Application = express();

app.disable("x-powered-by");

app.use(json());
app.use(compression());
app.use(urlencoded({ extended: true }));

if (app.get("env") === "production") {

  // in production mode run application from dist folder
  app.use(express.static(path.join(__dirname, "/../client")));
}
app.use('*', (req, res)  => {
  res.sendFile(path.join(__dirname, '/../client/index.html'));
});
// catch 404 and forward to error handler
app.use((req: express.Request, res: express.Response, next) => {
  const err = new Error("Not Found");
  next(err);
});

// production error handler
// no stacktrace leaked to user
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {

  res.status(err.status || 500);
  res.json({
    error: {},
    message: err.message,
  });
});

export { app };

you can clone this project and replace the angular app with yours

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM