Angular 5 HttpClient从wordpress REST api post response

时间:2018-04-12 20:01:29

标签: wordpress angular rest cookies httpclient

我已经搜索了很多,但我似乎无法找到问题的明确答案。很多类似的情况/解决方案,但没有一个适合我。

我的设置如下:

环境:在Angular 5之上运行的XAMP,Wordpress 4.9和Angular Material Design

后端(REST API服务器): 我有一个完全正常工作的Wordpress设置,在地址http://localhost/~XXXX/wordpress上顺利运行。 我打算只使用 后端,以便通过内置的json REST API接口向客户端提供数据,为此我设置了自定义/测试端点像这样:

add_action('rest_api_init', function () {

    register_rest_route('cookie-test/v1', 'set', [
      'methods' => 'POST',
      'callback' => function () {
          setcookie('cookieKey', $_POST['cookieValue'], time()+60*60*24*30);
          return [
            'responseKey' => 'responseValue',
          ];
      },
    ]);
});

实际上,我尝试实现的是前端的某种基于cookie的身份验证,不是基于wordpress的! 这个(伪)代码基本上是一个测试平台,以检查后端和前端之间正确的cookie功能/交换。

前端 :(部分内容)

// auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

@Injectable()
export class AuthService
{
    constructor(
        private http: HttpClient
    )
    {
    }

    cookieTest() {
        return this.http.post(
            'http://localhost/~XXXX/wordpress/wp-json/cookie-test/v1/set',
            {cookieValue: 'randomValue'},
            {
                observe: 'response', // Full response instead of the body only
                withCredentials: true, // Send cookies
            }
        );
    }
}

// login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';

@Component({
    selector   : 'login',
    templateUrl: './login.component.html',
    styleUrls  : ['./login.component.scss'],
})

export class LoginComponent implements OnInit
{
    loginForm: FormGroup;
    loginFormErrors: any;

    constructor(
        private formBuilder: FormBuilder,
        private authService: AuthService,
        private router: Router,
    )
    {
        this.loginFormErrors = {
            email   : {},
            password: {}
        };
    }

    ngOnInit()
    {
        this.loginForm = this.formBuilder.group({
            email   : ['', [Validators.required, Validators.email]],
            password: ['', Validators.required],
        });
    }

    onCookieTest()
    {
        this.authService.cookieTest()
            .subscribe(
                response => {
                    const keys: string[] = response.headers.keys();
                    console.log(keys);
                    console.log(response);
                },
                error => {
                    console.log(error);
                }
            );
    }
}

问题: 前端可以到达wordpress REST API端点,该端点反过来正确地响应角度' post'请求, ...但Cookie未在浏览器中设置!

我可以从浏览器的调试器控制台看到POST响应中的Set-Cookie标头有正确的字段,但显然浏览器(或Angular的HttpClient?)完全忽略它!

谷歌搜索我无法找到关于该对< Wordpress REST API> / Angular5的任何信息。所有类型的后端(ruby,laravel,java,C#等),但没有关于使用Angular5的HttpClient的Wordpress。

这些是标题:

请求(选项)

Access-Control-Request-Headers  content-type
Referer http://localhost:4200/auth/login
Origin  http://localhost:4200
Accept  */*
User-Agent  ...
Access-Control-Request-Method   POST

回复(OPTIONS)

Transfer-Encoding   Identity
Connection  Keep-Alive
X-Powered-By    PHP/7.0.14
Access-Control-Allow-Methods    OPTIONS, GET, POST, PUT, PATCH, DELETE
Access-Control-Expose-Headers   X-WP-Total, X-WP-TotalPages
Vary    Origin
Access-Control-Allow-Headers    x-wp-nonce, Authorization, Content-Type
Server  Apache/2.4.16 (Unix) PHP/7.0.14 OpenSSL/0.9.8zg
Content-Type    application/json; charset=UTF-8
Access-Control-Allow-Credentials    true
Date    Thu, 12 Apr 2018 19:20:43 GMT
Access-Control-Allow-Origin http://localhost:4200
Keep-Alive  timeout=5, max=100
X-Content-Type-Options  nosniff
X-Robots-Tag    noindex
Link    <http://localhost/~XXXX/wordpress/wp-json/>; rel="https://api.w.org/"
Allow   POST

请求(POST)

DNT 1
Content-Type    application/json
Referer http://localhost:4200/auth/login
Accept  application/json, text/plain, */*
User-Agent  ...
Origin  http://localhost:4200

回复(POST)

Transfer-Encoding   Identity
Connection  Keep-Alive
X-Powered-By    PHP/7.0.14
Access-Control-Allow-Methods    OPTIONS, GET, POST, PUT, PATCH, DELETE
Set-Cookie  cookieKey=randomValue; expires=Sat, 12-May-2018 19:20:53 GMT; Max-Age=2592000
Access-Control-Expose-Headers   X-WP-Total, X-WP-TotalPages
Vary    Origin
Access-Control-Allow-Headers    x-wp-nonce, Authorization, Content-Type
Server  Apache/2.4.16 (Unix) PHP/7.0.14 OpenSSL/0.9.8zg
Content-Type    application/json; charset=UTF-8
Access-Control-Allow-Credentials    true
Date    Thu, 12 Apr 2018 19:20:52 GMT
Access-Control-Allow-Origin http://localhost:4200
Keep-Alive  timeout=5, max=100
X-Content-Type-Options  nosniff
Link    <http://localhost/~XXXX/wordpress/wp-json/>; rel="https://api.w.org/"
X-Robots-Tag    noindex
Allow   POST

提前感谢您提供任何帮助/提示

1 个答案:

答案 0 :(得分:1)

您需要在后端指定路径(例如根路径)

setcookie('cookieKey', $_POST['cookieValue'], time()+60*60*24*30, '/')

如果您在设置Cookie时没有指定路径,那么它只能在当前路径(.../wp-json/cookie-test/v1/set)上使用,这意味着Cookie不会获得如果您在该域上尝试不同的路径,则会在将来的请求中发送到您的后端