Node.js/Express redirect all to angular 2 page

拥有回忆 提交于 2019-12-31 03:22:27

问题


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;


来源:https://stackoverflow.com/questions/43869961/node-js-express-redirect-all-to-angular-2-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!