Home > Software engineering >  Wordpress (WooCommerce) cross-origin issue for create customers
Wordpress (WooCommerce) cross-origin issue for create customers

Time:01-14

i am testing from frontend post data to backend wordpress (woocommerce) to create customers account. i tested with postman and it works awesome but if i post data from frontend to backend i have a cross-origin issue.

i know cross-origin issue is 2 domain prevent to share resource but i tried kind alot way but still cant get the problem fix. anyone have any idea how should i solve this ?

Error :

Cross Origin Problem Refused to set unsafe header "User-Agent" from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

nuxt.js / pages / register.vue

 import {
        createWooComCustomer
    } from '@/plugins/woocomapi.js'
    export default {
        data() {
            return {
                email: '',
                username: '',
                password: ''
            }
        },
        methods: {
            async registerUsers() {
                await createWooComCustomer(this.email, this.username, this.password).then((response) => {
                    console.log(respons)
                }).catch((e) => {
                    throw new Error('failure create customer')
                })
            },
        },
        mounted() {}
    }

nuxt.js / plugins / woocomapi.js (using woocommerce/woocommerce-rest-api package)

import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

// local test api
const api = new WooCommerceRestApi({
    url: "http://localhost:3080",
    consumerKey: "ck_xxx",
    consumerSecret: "cs_xxx",
    version: "wc/v3",
});


// fetch all products from WooCommerce //
export async function fetchWooComProducts() {
    try {
        const response = await api.get("products");
        return response
    } catch (error) {
        throw new Error(error);
    }
}

export async function createWooComCustomer(customer_email, customer_username, customer_password) {
    try {
        const response = await api.post("customers", {
            data: {
                email: customer_email,
                username: customer_username,
                password: customer_password
            }
        })
        return response
    } catch (error) {
        throw new Error(error);
    }
}

wordpress / .htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>
# END WordPress

wordpress / wp-content / themes / twentytwentyone / functions.php

add_action( 'init', 'handle_preflight' );
function handle_preflight() {
    $origin = get_http_origin();
    if ( $origin == 'http://localhost:3000/' ) {
        // You can set more specific domains if you need
        header("Access-Control-Allow-Origin: " . $origin);
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header("Access-Control-Allow-Credentials: true");
        header( 'Access-Control-Allow-Headers: Authorization' );

        if ( 'OPTIONS' == $_SERVER['REQUEST_METHOD'] ) {
            status_header(200);
            exit();
        }
    }
}

i did a restful api logs, when postman successful create it was request "POST" but this one always send as "GET" and fail to create even i am sure is post i am sending. i tried to put nginx on allow-origin "*" also tried put into apcache server directly but none of them work, being stuck for 3 days and i ran out of idea how to fix this one, if anyone got some good advice after looking at the code, please share with me, will be greatful.

here is my full repo : https://github.com/differentMonster/woonuxtpress

CodePudding user response:

Found this person Wp Plugins that save life, hopefully someone will find it useful having Cross Origin pain on headless wordpress.

git repo : https://github.com/mandrasch/wp-configure-cors-origin

  •  Tags:  
  • Related