【问题标题】:Route error in Angular 6/ExpressAngular 6/Express 中的路由错误
【发布时间】:2018-06-14 11:29:10
【问题描述】:

我正在开发一个 nodeJS/Angular 6/Express 应用程序。 “后端”只有 1 条 express 路线,而 angular 有许多路线。

我在本地运行它没有问题,但是当我尝试在 Azure 上部署它时,Angular 路由可以正常工作,但后端路由不能正常工作(它将我重定向到根 url)。

我认为 Angular 优先考虑后端路由。

这里有一些文件:

server.js:

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const fetch = require('node-fetch');
const publicweb = './dist/forms';
const app = express();
app.use(express.static(publicweb));


app.use('/api/test', (req, res) => {
   res.send("test");
});

app.get('*', (req, res) => {
  res.sendFile('index.html', { root: publicweb });
});

const port = '1337';
app.listen(port, () => console.log(`API running on localhost:${port}`));

web.config:

<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="server.js" verb="*" modules="iisnode" />
</handlers>
  <rewrite>
    <rules>
            <rule name="Express.js URIs">
      <match url="api/*" />
      <action type="Rewrite" url="server.js" />
    </rule>
      <rule name="Angular" stopProcessing="true">
        <match url="/*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" 
         negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>
</configuration>

package.json:

"start" : "node src/server.js"

app-routing.module.ts :

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { RetailComponent } from './retail/form/retail.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: '/',
    pathMatch: 'full'
  },

 {
    path: 'retail',
    component: RetailComponent
 }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {

}

When I deploy that app on Azure, and I try to access /api/test

My build definition in Azure

非常感谢您的回答!

【问题讨论】:

  • 您是通过 http 调用调用 api/test 吗?还是来自路由呼叫?
  • 我从 http 调用它
  • 如果你从 http 调用,你不能得到照片中的错误,该错误仅来自路由
  • 是的,你是对的。当我在邮递员中拨打电话(api/test)时,我得到 index.html 文件的代码作为响应

标签: node.js angular azure express


【解决方案1】:

我认为你所有的 get 请求都映射到这段代码

app.get('*', (req, res) => {
    enter code here`res.sendFile('index.html', { root: publicweb });
});

这就是为什么您在对服务器的查询中收到 index.html

app.use() 将用于应用中间件,因此在中间件工作结束后,app.get() 方法将被执行,因此您会得到 index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    相关资源
    最近更新 更多