如何从服务器请求通用角度发送Cookie中的令牌?

时间:2019-05-30 20:09:13

标签: javascript node.js angular typescript angular-universal

我需要在请求标头“ Cookie:令牌”中从服务器端发送到API 在角度通用中,对于服务器的Http请求方法,我使用axios。当我尝试使用Interceptor更改标头时,如果我像axios的第三个参数那样发送静态cookie,则我会收到错误消息“拒绝设置不安全的标头'Cookie'” ,但我遇到了一些麻烦在其中动态插入令牌。

request.servise.ts

    import { RequestBody } from './models/request-body.model';
    import axios from 'axios';
    import {AxiosInstance} from 'axios';

    export class Request {
        http: AxiosInstance = axios;
        constructor() {}
        async test(): Promise<any> {
        const  params = {
                param1: 1,
                param2: 2,
                param3: 3,
            }
            try {
            return this.basicRequest('https://some-request.url', params);
            } catch (e) {
            console.error('Unknown exception: ', e);
            return null;
            }
        }

        private basicRequest(url, params) {
            const request = new RequestBody('2.0', 'someMethod', Math.floor(Math.random() * (9999999 - 1000000)) + 1000000, params);
            return this.http.post(url, request);
        }
    }

projects.ts(服务器路由器控制器)

      import {Router} from 'express';
      import {Request} from '../../shared/request.service';



      const router: Router = Router();

      router.get('/test', async function(req, res, next){

        const request = new Request();
        try {
          const projects = (await request.test()).data.result.records;
          res.json(projects);
        } catch (e) {
          console.error(e);
        }
      });


      export const ProjectsController: Router = router;

1 个答案:

答案 0 :(得分:0)

默认情况下,使用HttpClient时,角度通用不传输cookie。因此,您需要手动进行操作,但是您会得到提到的错误。

建议in that universal github issue的一种可能的解决方法是绕过xhr2对不安全标头的默认安全行为

server.ts

import * as xhr2 from 'xhr2';
xhr2.prototype._restrictedHeaders = {};