简体   繁体   中英

Angular Http post request not seen by $_POST on backend php

I'm building a PHP custom endpoint for a WordPress site to submit a form on woocommerce product page, add to cart form to be specific.

So I have a mobile app build on ionic 4 / angular 8 that needs to send a post request to the above endpoint.

The problem is that the post request body from angular not identify by $_POST on PHP code so $_POST return null and the product not getting added on the cart!!

But when testing this using postman the request success and adding the product to cart successfully.

I tried to get angular JSON body on PHP side and succeed and get a success response but the product not adding to the cart means the form requires a specific way to send similar to the postman request.

The PHP code pretty simple:

function yith_custom_add_item( WP_REST_Request $request ) {
    $currentuserid_fromjwt = get_current_user_id();
    $user = get_user_by( 'id', $currentuserid_fromjwt );


    if( $user ) {

        $product_id = $_GET['id'];
        $url = get_permalink( $product_id );

        $cookie = 'wordpress_logged_in_856ec7e7dd32c9b2fc11b366505cf40d' . '=' . wp_generate_auth_cookie($currentuserid_fromjwt, time() + (10 * 365 * 24 * 60 * 60), 'logged_in') . ';';

        $cookie .='_icl_current_admin_language_d41d8cd98f00b204e9800998ecf8427e=en; wp_woocommerce_session_856ec7e7dd32c9b2fc11b366505cf40d=171%7C%7C1575326201%7C%7C1575322601%7C%7Cab91a0f0bbe0f3d5ae90dd5bdf7e396d; wfwaf-authcookie-5372c020d00bf5e1ea6c81123ff21ec1=171%7C%7C4574b4a9b1b62c8c7a1c1ae24cd4bd26d279bb5670fe87bcf7eb210835e43f22; _icl_current_language=en; PHPSESSID=5ed2009813f86633694a25e297d4ee06; wordpress_logged_in_856ec7e7dd32c9b2fc11b366505cf40d=deleted; woocommerce_items_in_cart=1; woocommerce_cart_hash=086ae7e00c53740163451a538fe8a9fc';


        $angular_json = json_decode(file_get_contents("php://input"));


        if ( !empty($_POST) ) {
            $response = wp_remote_post( $url, array(
                'headers' => array(
                   'Cookie' => $cookie,
                   'Authorization' => $request->get_header('Authorization'),
                   'Content-Type' => 'application/x-www-form-urlencoded',
                ),
                'body'    => $_POST,

            ));

            return $response;
        } elseif ( !empty($angular_json) ) {
            $response = wp_remote_post( $url, array(
                                                    'headers' => array(
                                                                       'Cookie' => $cookie,
                                                                       'Authorization' => $request->get_header('Authorization'),
                                                                       'Content-Type' => 'application/x-www-form-urlencoded',
                                                                       ),
                                                    'body'    => $angular_json,

                                                    ));

            return $angular_json;
        } else {
            return "Nothing to show";
        }

    }

}

The Angular code: ( service )

  addYithCompositeToCart(id: any, data: any) {

    const { token } = JSON.parse(localStorage.getItem('user'));

    let headers = {
      'Content-Type': 'x-www-form-urlencoded; charset=UTF-8',
      "Authorization": `Bearer ${token}`,
    };

    // let headers = new HttpHeaders();
    // headers
    //   .set('Content-type', 'x-www-form-urlencoded;')
    //   .set('Authorization', `Bearer ${token}`);

    this.http.post(`${environment.host}yith-composite/add-item?id=${id}`, data, {
      headers
    })
      .toPromise()
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.log(error);
      });
  }

The component ( trigger by clicking ):

addToCart() {
  const data = {
        ywcp_selection: Object.assign({}, ...this.options.map(object => ({ [object.productSerial]: -1 }))),
        ywcp_variation_id: Object.assign({}, ...this.options.map(object => ({ [object.productSerial]: object.variation.variation_id }))),
        ywcp_quantity: Object.assign({}, ...this.options.map(object => ({ [object.productSerial]: 1 }))),
        ywcp_selected_product_value: Object.assign({}, ...this.options.map(object => ({ [object.productSerial]: object.productId }))),
        quantity: 1,
        'add-to-cart': this.product.id
      };

      this.cartService.addYithCompositeToCart(this.product.id, data);
}

The postman request在此处输入图片说明

Did you try specifying the content-type in the HttpOptions and that it is json data that you are providing in the body ?

For example :

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization": `Bearer ${token}`,
  })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM