angular 普遍未达到 api
angular universal not reaching api
我目前正在尝试构建一个 angular 通用应用程序(使用 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 通用。所以以下将不起作用,因为没有为前面定义的'/api'route/handler。
this.httpClient.get<any>("/api")
启动angular通用渲染模式的说明在这里
https://github.com/angular/universal-starter#production-also-for-testing-ssrpre-rendering-locally
此外,使用 angular 通用时,执行 ajax 调用时不能使用相对 URL。您必须指定完整的 url(如果 https 不是 80 或 443,则协议/域/端口)
所以现在,您应该使用
this.httpClient.get<any>("http://localhost:4000/api")
如果您的 angular 通用 运行 在本地主机的端口 4000 上
我目前正在尝试构建一个 angular 通用应用程序(使用 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 通用。所以以下将不起作用,因为没有为前面定义的'/api'route/handler。
this.httpClient.get<any>("/api")
启动angular通用渲染模式的说明在这里 https://github.com/angular/universal-starter#production-also-for-testing-ssrpre-rendering-locally
此外,使用 angular 通用时,执行 ajax 调用时不能使用相对 URL。您必须指定完整的 url(如果 https 不是 80 或 443,则协议/域/端口)
所以现在,您应该使用
this.httpClient.get<any>("http://localhost:4000/api")
如果您的 angular 通用 运行 在本地主机的端口 4000 上