node.js - angular universal 达不到 api

标签 node.js angular rest express angular-universal

我目前正在尝试构建一个 Angular 通用的应用程序(使用 https://github.com/angular/universal-starter ),但我遇到了一个问题。 当我尝试访问我的 API 时,我的应用程序似乎没有找到它。

这是我开始写的基本代码:

服务器.ts

import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';

import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';

var apiRoute = require("./routes/api");

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');

// Our index.html we'll use as our template
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');

// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

/* - Example Express Rest API endpoints -
  app.get('/api/**', (req, res) => { });
*/

app.use("/api/", apiRoute);




// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser'), {
  maxAge: '1y'
}));

// ALl regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

API.js

var express = require('express');
var router = express.Router();

router.get("/", function (req, res, next) {
    console.log("ok test");
    res.status(200).json({
        title: "Success",
        obj: "okSuccess"
    });
});

module.exports = router;

应用程序模块.ts

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import {TransferHttpCacheModule} from '@nguniversal/common';
import { HttpClientModule } from '@angular/common/http';
import { HomeService } from './home/home.service';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
  ],
  imports: [
    HttpClientModule,
    BrowserModule.withServerTransition({appId: 'my-app'}),
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full'},
      { path: 'lazy', loadChildren: './lazy/lazy.module#LazyModule'},
      { path: 'lazy/nested', loadChildren: './lazy/lazy.module#LazyModule'}
    ]),
    TransferHttpCacheModule,
  ],
  providers: [
    HomeService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

home.component.ts

import { Component, OnInit } from '@angular/core';
import { HomeService } from './home.service';

@Component({
  selector: 'app-home',
  template: `<h3>{{ message }}</h3>`
})
export class HomeComponent implements OnInit {
  public message: string;

  constructor(private homeService: HomeService) { }

  ngOnInit() {
    this.message = 'Hello';
    console.log(this.homeService.apiCall());
   }
}

home.service.ts

import { Injectable } from "@angular/core";
import { Headers, Http, Response } from "@angular/http";
import { HttpClient, HttpHeaders, HttpParams, HttpRequest } from '@angular/common/http';
import 'rxjs/Rx';
import { Observable } from "rxjs/Observable";


@Injectable()
export class HomeService {

    constructor(private httpClient: HttpClient) { }

    apiCall() {
        return this.httpClient.get<any>("/api")
        .map((response) => {
                console.log(response);
                return response;
            })
            .subscribe((response) => {
                console.log(response);
                return response;
            });
    }
}

我通过键入 npm run start 开始在开发模式下构建,但随后出现以下错误

enter image description here 我真的不明白为什么会出现这个错误,好像 express 没有添加我的路线。

最佳答案

注意:如果您查看 package.json 文件,您会注意到 npm run start 仅调用 ng serve,因此它没有使用 angular universal。所以以下将不起作用,因为没有为前端定义的“/api”路由/处理程序。

this.httpClient.get<any>("/api")

启动 Angular 通用渲染模式的说明在这里 https://github.com/angular/universal-starter#production-also-for-testing-ssrpre-rendering-locally

此外,使用angular universal时,执行ajax调用时不能使用相对URL。您必须指定完整的 url(如果 https 不是 80 或 443,则为协议(protocol)/域/端口)

所以现在,你应该使用

this.httpClient.get<any>("http://localhost:4000/api")

如果你的 Angular Universal 在本地主机上的端口 4000 上运行

关于node.js - angular universal 达不到 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48987666/

相关文章:

java - 如何确保 Jersey 中的程序化资源?

javascript - 在 Chrome 扩展中使用 Node.js 和 Express.js

angular - 如何在页面加载时触发 Toast?

rest - 如何使用 EMS 文档属性创建 YAML 文档

javascript - Angular 2 - 带有 Assets 的网址

javascript - Angular 中的嵌套形式数组

rest - grails 3.3.9-从restfulController扩展失败,出现 “No default constructor found”

node.js - 如何取消初始化 NPM?

javascript - 排除 gulp.watch 中的子目录

javascript - Heroku 返回 400 错误请求响应 (Socket.IO Node.js)