简体   繁体   English

使用nodejs服务器打角度路线时出错

[英]error in hitting the angular routes using nodejs server

I have my homepage at locahost:3000 , and there is a link in my homepage to login page at /login . 我的主页位于locahost:3000 ,并且主页上有一个链接到/login登录页面。

When I clicked at that link, It reaches to the login page. 当我单击该链接时,它会到达登录页面。 But when I refresh that page it shows error Cannot GET /login . 但是,当我刷新该页面时,它显示错误Cannot GET /login Again when I am clicking on that link from homepage, it reaches to login page But when I am trying to enter the url localhost:3000/login it gives same error Cannot GET /login . 同样,当我从首页单击该链接时,它会到达登录页面。但是当我尝试输入url localhost:3000/login它给出了同样的错误Cannot GET /login

My app.js is - 我的app.js是-

    app.use(express.static(__dirname + '/dist/newApp'));

    app.get('/', (req,res)=>{
      res.sendFile(path.join(__dirname, ''));
    });

and my angular routes is - 我的弯角路线是-

export const myRoutes: Routes = [
   {
    path: ' ',
    component: HomepageComponent
   },
  {
    path: 'login',
    component: LoginComponent
  }]

And I am using routerLink="/login" instead of href for the link. 我正在使用routerLink="/login"代替该链接的href

I don't know why this is happening. 我不知道为什么会这样。

My server running process is -- npm build and then npm start 我的服务器运行过程是npm buildthen npm start

And If I am running my angular server as ng serve , and then enter the url localhost:3000/login directly in browser, it is working. 并且如果我以ng serve运行我的角度服务器,然后直接在浏览器中输入url localhost:3000/login ,则它可以正常工作。

But When I am running nodejs server it again causing problem. 但是当我运行nodejs服务器时,它再次导致了问题。

I think the problem is that on running nodejs server, angular server stops runnning. 我认为问题是在运行nodejs服务器上,角度服务器停止了运行。

Can someone explain the reason for this and how to run both the server. 有人可以解释其原因以及如何同时运行两个服务器。

You need to add a final * route to catch any paths it doesn't recognize (such as /login ), and return the index.html file. 您需要添加一个最终*路由来捕获它无法识别的任何路径(例如/login ),并返回index.html文件。

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '/dist/newApp/index.html'));
});

It's very important that you place this after any other route declarations. 将其放置在任何其他路由声明之后非常重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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