centerofme
centerofme

Reputation: 51

Express serving angular routes

I am trying to get my angular routes working in express so far it will load the page index.html and if you navigate from there it will use the routes just fine, however if you open a new browser and try to go directly to a route ('deep link') it will not work... (the routes do work in ng serve)

here's what i'm using to get it to serve the index.html

    app.use(express.static(__dirname + '/dist'));
    app.use("*",function(req,res){
      res.sendFile(path.join(__dirname,"/dist/index.html"));
    });

If i try to go to localhost:3000 it works fine... again as i navigate from that page those routes work fine too but if i try to do localhost:3000/room/3290sfda9328fa98 (that page contains a route :id) then it does not work

Here is the angular side of the routes

export const routes: Routes = [
  { path: '', component: StartscreenComponent },
  { path: 'room/:id', component: RoomComponent },
  { path: 'createroom', component: StartroomComponent }
];

The error you get back looks like this:

ReferenceError: path is not defined
    at /Documents/angular8/nodechat/index.js:18:18
    at Layer.handle [as handle_request] (/Documents/angular8/nodechat/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:317:13)
    at /Documents/angular8/nodechat/node_modules/express/lib/router/index.js:284:7
    at param (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:354:14)
    at param (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:365:14)
    at Function.process_params (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:410:3)
    at next (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:275:10)
    at SendStream.error (/Documents/angular8/nodechat/node_modules/serve-static/index.js:121:7)
    at SendStream.emit (events.js:189:13)

Here is a bit more of the index.js file

const express = require('express');
const app = express();
const router = express.Router();
// const proxy = require('express-http-proxy');
const helmet = require('helmet');
app.use(helmet());
const http = require('http').createServer(app);
const io = require('socket.io')(http);
app.use(express.static(__dirname + '/dist'));
app.use("*",function(req,res){
    res.sendFile(path.join(__dirname,"/dist/index.html"));
});
http.listen(3000, () => {
  console.log('listening on *:3000');
});

Upvotes: 2

Views: 98

Answers (2)

quicklikerabbit
quicklikerabbit

Reputation: 3556

You need to require(path) before you can use it. Add this to the top of your index.js:

const path = require('path')

Upvotes: 1

alexvdvalk
alexvdvalk

Reputation: 1234

It may be becuase you're directly serving the index.html file. Try this?

res.sendFile(path.join(__dirname,"/dist/"));

or

res.sendFile(path.join(__dirname,"/dist"));

Upvotes: 0

Related Questions