Node.js/Express redirect all to angular 2 page

2020-04-16 18:35发布

问题:

I am creating an Angular 2 app with Node.js and Express.

The problem I am having is that my routes file doesnt work with a wildcard. Everytime I visit the page with anything other then / (for example /test) it says the following: ReferenceError: path is not defined

My server.js:

const express = require('express');
const app = express();
const path = require('path');
const routes = require('./routes');
const data = require('./articles.json');

app.use(express.static(path.join(__dirname, '/dist')));
app.use('/', routes);

app.listen(8080, function () {
  console.log('App started on port 8080');
});

My /routes/index.js:

const routes = require('express').Router();

routes.get('*', function (req, res) {
  res.sendFile(path.join(__dirname + '/dist/index.html'));
});

module.exports = routes;

So what am I doing wrong here?

回答1:

You need to require the path package in your index.js too

/routes/index.js

const path = require('path');
const routes = require('express').Router();

routes.get('*', function (req, res) {
  res.sendFile(path.join(__dirname + '/dist/index.html'));
});

module.exports = routes;