繁体   English   中英

角度普遍没有达到api

[英]angular universal not reaching api

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

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

server.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;

app.module.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开始构建开发模式但是我得到了以下错误

在此输入图像描述 我真的不明白为什么我得到这个错误,好像快递不添加我的路线。

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

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

有关启动角度通用渲染模式的说明,请访问https://github.com/angular/universal-starter#production-also-for-testing-ssrpre-rendering-locally

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

所以现在,你应该使用

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

如果您的angular universal在localhost上的端口4000上运行

暂无
暂无

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

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