如何在Angular Universal中将cookie抛出节点服务器传递给REST API?

如何在Angular Universal中将cookie抛出节点服务器传递给REST API?,angular,cookies,server-side-rendering,Angular,Cookies,Server Side Rendering,我有一个带有服务器端渲染的Angular应用程序。我习惯于只在服务器端执行一个rest请求,所以我将这些代码放在if(isPlatformServer(this.platformId))块中 应用程序组件.ts import {Component, Inject, OnInit, PLATFORM_ID} from "@angular/core"; import {HttpClient, HttpHeaders} from "@angular/common/http"; import "rxjs

我有一个带有服务器端渲染的Angular应用程序。我习惯于只在服务器端执行一个rest请求,所以我将这些代码放在if(isPlatformServer(this.platformId))块中

应用程序组件.ts

import {Component, Inject, OnInit, PLATFORM_ID} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import "rxjs/add/operator/map";
import {Http} from "@angular/http";
import {isPlatformBrowser, isPlatformServer} from "@angular/common";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  constructor(private http: HttpClient, @Inject(PLATFORM_ID) private platformId: Object){ }

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      /* Client only code. */
    }

    if (isPlatformServer(this.platformId)) {
      /* Server only code. */
      this.http.get('http://localhost:8080/tracking', { withCredentials: true }).subscribe(data => {
        console.log("Init tracking")
      });
    }
  }
}
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";
// Express Engine
import {ngExpressEngine} from "@nguniversal/express-engine";
// Import module map for lazy loading
import {provideModuleMap} from "@nguniversal/module-map-ngfactory-loader";
import {CookieService} from "ngx-cookie-service";

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

// Express server
const app = express();
let cookieParser = require('cookie-parser');
app.use(cookieParser());

const PORT = process.env.PORT || 4200;
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');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    CookieService,
    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) => { });
*/

// 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) => {
  console.log('Cookies req: ', req.cookies);
  res.render('index', { req });

});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});
一切正常,这个http.get只在服务器端调用,但我的API上的httprequest没有cookie。因此,在我的节点服务器中,我添加了cookie抛出cookie解析器:

let cookieParser = require('cookie-parser');
app.use(cookieParser()); 
我在console.log(req.cookies)中看到了它们,但它们仍然没有出现在API中

server.ts

import {Component, Inject, OnInit, PLATFORM_ID} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import "rxjs/add/operator/map";
import {Http} from "@angular/http";
import {isPlatformBrowser, isPlatformServer} from "@angular/common";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  constructor(private http: HttpClient, @Inject(PLATFORM_ID) private platformId: Object){ }

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      /* Client only code. */
    }

    if (isPlatformServer(this.platformId)) {
      /* Server only code. */
      this.http.get('http://localhost:8080/tracking', { withCredentials: true }).subscribe(data => {
        console.log("Init tracking")
      });
    }
  }
}
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";
// Express Engine
import {ngExpressEngine} from "@nguniversal/express-engine";
// Import module map for lazy loading
import {provideModuleMap} from "@nguniversal/module-map-ngfactory-loader";
import {CookieService} from "ngx-cookie-service";

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

// Express server
const app = express();
let cookieParser = require('cookie-parser');
app.use(cookieParser());

const PORT = process.env.PORT || 4200;
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');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    CookieService,
    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) => { });
*/

// 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) => {
  console.log('Cookies req: ', req.cookies);
  res.render('index', { req });

});

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

如何传递cookie throw node并在API中的rest端点上获取它们?

Angular universal在执行SSR时不会自动将从客户端请求接收到的cookie设置为其所有HTTP请求,因为它无法验证cookie是否应附加到向域发出的特定HTTP请求

尽管您可以通过如下设置cookie头为
http.get(url,options)
request设置它

// DO THIS only on server
if(isPlatformServer){
    // options: RequestOptionsArgs
     let options = {};
     options.headers = new Headers();
     options.headers.set('cookie', 'cookies that you need to attach');
}
http.get(url, options)
查看以下文章了解详细信息。

我解决了这个问题。现在,问题是cookie不是从RESTAPI(Spring)到节点(http拦截器)的。请看这个问题