如何在Nodejs中处理angular2路径?

Rhu*_*esh 16 node.js angular2-routing angular

我正在使用Angular2开发NodeJS应用程序.在我的应用程序中,我有一个主页和搜索页面.对于主页,我有一个HTML页面,它将为localhost:3000 /和主页用户导航到搜索,localhost:3000 / 我通过angular2路由处理的搜索页面.

我没有搜索页面的页面,其视图由angular2呈现.但是当我直接命中localhost:3000/search因为我在我的节点应用程序中没有这个路由时它会给出错误.

我不知道如何在节点应用程序中处理这个?

use*_*086 28

如果localhost:3000/search直接在浏览器导航栏中输入,浏览器会向服务器发出"/搜索"请求,这可以在控制台中看到(请确保选中"保留日志"按钮).

Navigated to http://localhost:3000/search
Run Code Online (Sandbox Code Playgroud)

如果运行完全静态服务器,则会生成错误,因为服务器上不存在搜索页面.例如,使用express,您可以捕获这些请求并返回index.html文件.angular2引导程序启动,并且@RouteConfig中描述的/ search路由被激活.

// example of express()
let app = express();
app.use(express.static(static_dir));

// Additional web services goes here
...

// 404 catch 
app.all('*', (req: any, res: any) => {
  console.log(`[TRACE] Server 404 request: ${req.originalUrl}`);
  res.status(200).sendFile(index_file);
});
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案.此外,如果您不使用TypeScript,它可能类似于`app.all('*',function(req,res){res.status(200).sendFile(path.join(__ dirname,'/ index). html'));});` (8认同)