用于创建客户的 Wordpress (WooCommerce) 跨源问题

Wordpress (WooCommerce) cross-origin issue for create customers

我正在测试从前端 post 数据到后端 wordpress (woocommerce) 以创建客户帐户。我用 postman 进行了测试,效果很好,但是如果我 post 从前端到后端的数据,我有一个跨源问题。

我知道跨域问题是 2 域阻止共享资源,但我尝试了很多方法但仍然无法解决问题。任何人都知道我应该如何解决这个问题?

错误:

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/页数/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/插件/woocomapi.js(使用woocommerce/woocommerce-rest-api包)

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=
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$  [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();
        }
    }
}

我做了一个 restful api 日志,当 postman 成功创建时它是请求“POST”但是这个总是作为“GET”发送并且失败创建甚至我确定是 post 我正在发送。我尝试将 nginx 置于 allow-origin "*" 上,也尝试直接将其放入 apcache 服务器,但 none 其中的工作正常,被卡住了 3 天,我 运行 不知道如何解决这个问题,如果有人在看完代码后得到了一些好的建议,请与我分享,将不胜感激。

这是我的完整回购协议: https://github.com/differentMonster/woonuxtpress

wordpress / wp-content / themes / 你的wordpress的主题 select / functions.php

function handle_preflight()
{
    // set header for rest API (and other resources as well?)
    header("Access-Control-Allow-Origin: " . "*");
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
    if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
        status_header(200);
        exit();
    }
}

add_action('init', __NAMESPACE__ . '\handle_preflight');

删除 if 检查 $origin 如果你有任何 'POST 或 'PUT' on the if 'POST' == $_SERVER['REQUEST_METHOD'] switch to 'OPTIONS' 因为 OPTIONS 更广泛地接受所有。

如果您想知道是否应该更改服务器上的 CORS 或 .htaccess,请只关注 wordpress 部分,因为我尝试了所有部分以查看任何工作,这会造成更多混乱。让你的帽子尽可能简单。

wordpress/.htacess

# 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]
</IfModule>
# END WordPress

也不需要从前端或 nginx 发送任何东西 header,在 js 部分删除数据 object,不知何故 woocommerce rest api 在没有 object 数据换行。

nuxt.js/插件/woocomapi.js

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