首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >angular universal未到达api

angular universal未到达api
EN

Stack Overflow用户
提问于 2018-02-26 19:38:59
回答 1查看 2.2K关注 0票数 3

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

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

server.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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开始在开发模式下构建,但随后得到了以下错误

我真的不明白为什么我得到这个错误,它似乎快递没有添加我的路线。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-26 21:24:40

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

代码语言:javascript
复制
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)

所以现在,您应该使用

代码语言:javascript
复制
this.httpClient.get<any>("http://localhost:4000/api")

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48987666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档