PhoneGap中文网

 找回密码
 立即注册
查看: 23407|回复: 1
打印 上一主题 下一主题

Angular4 Angular5 cookie跨域以及相关配置http credentials 配置

[复制链接]

493

主题

2035

帖子

6894

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
6894
跳转到指定楼层
楼主
发表于 2018-9-28 16:34:35 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
Angular4 Angular5 cookie跨域以及相关配置



1、Angular4 Angular5 默认是发送请求的时候不会带上cookie的,需要通过设置withCredentials: true来解决。 这个时候需要注意需要后端配合设置

header信息 Access-Control-Allow-Credentials:true

Access-Control-Allow-Origin不可以为 '*',因为 '*' 会和 Access-Control-Allow-Credentials:true 冲突,需配置指定的地址

如果后端设置 Access-Control-Allow-Origin: '*', 会有如下报错信息


  1. Failed to load http://localhost:8090/category/lists: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8081' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
复制代码



后端配置缺一不可,否则会出错,贴上我的后端示例:

  1. const express = require('express')
  2. const app = express()
  3. const cors = require('cors') // 此处我的项目中使用express框架,跨域使用了cors npm插件

  4. app.use(cors{
  5.             credentials: true,
  6.             origin: 'http://localhost:8081', // web前端服务器地址
  7.             // origin: '*' // 这样会出错
  8.         })
复制代码


成功之后,可在请求中看到


Angular4 Angular5 cookie跨域以及相关配置http with  credentials 配置

  1. import { Injectable } from 'angular2/core';
  2. import { IjobCard } from '../jobCard/jobCard';
  3. import { Http, Response } from 'angular2/http';
  4. import { Observable } from 'rxjs/Observable';
  5. import { Icredentials } from './credentials';

  6. @Injectable()
  7. export class LoginService {
  8.     private _loginUrl = 'MyUrl/Login';
  9.     loginCred: Icredentials = {
  10.         "filed1": "dummy1",
  11.         "filed2": "dummy2",
  12.         "filed3": "dummy3"
  13.     };

  14.     private headers = new Headers({ 'Content-Type': 'application/json' });

  15.     constructor(private _http: Http){

  16.     }

  17.     login(): Observable<any>[] {
  18.         return this._http.post(this._loginUrl, JSON.stringify(this.loginCred),
  19.             { headers: this.headers, withCredentials: true })
  20.             .map((response: Response) => <any[]>response.json())
  21.             .catch(this.handleError);

  22.     }
复制代码




来源:https://stackoverflow.com/questions/39437956/angular2-http-with-credentials-cant-add-cookies





回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐 上一条 /1 下一条

ionic4视频教程

Archiver|手机版|小黑屋| PhoneGap中文网 ( 京ICP备13027796号-1 )  

GMT+8, 2024-4-26 09:10 , Processed in 0.044310 second(s), 29 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表