|
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: '*', 会有如下报错信息
- 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.
复制代码
后端配置缺一不可,否则会出错,贴上我的后端示例:
- const express = require('express')
- const app = express()
- const cors = require('cors') // 此处我的项目中使用express框架,跨域使用了cors npm插件
- app.use(cors{
- credentials: true,
- origin: 'http://localhost:8081', // web前端服务器地址
- // origin: '*' // 这样会出错
- })
复制代码
成功之后,可在请求中看到
Angular4 Angular5 cookie跨域以及相关配置http with credentials 配置
- import { Injectable } from 'angular2/core';
- import { IjobCard } from '../jobCard/jobCard';
- import { Http, Response } from 'angular2/http';
- import { Observable } from 'rxjs/Observable';
- import { Icredentials } from './credentials';
- @Injectable()
- export class LoginService {
- private _loginUrl = 'MyUrl/Login';
- loginCred: Icredentials = {
- "filed1": "dummy1",
- "filed2": "dummy2",
- "filed3": "dummy3"
- };
- private headers = new Headers({ 'Content-Type': 'application/json' });
- constructor(private _http: Http){
- }
- login(): Observable<any>[] {
- return this._http.post(this._loginUrl, JSON.stringify(this.loginCred),
- { headers: this.headers, withCredentials: true })
- .map((response: Response) => <any[]>response.json())
- .catch(this.handleError);
- }
复制代码
来源:https://stackoverflow.com/questions/39437956/angular2-http-with-credentials-cant-add-cookies
|
|