【问题标题】:Wordpress (WooCommerce) cross-origin issue for create customers用于创建客户的 Wordpress (WooCommerce) 跨域问题
【发布时间】:2022-01-11 13:20:36
【问题描述】:

我正在测试从前端发布数据到后端 wordpress (woocommerce) 以创建客户帐户。我用邮递员进行了测试,效果很好,但是如果我将数据从前端发布到后端,我就会遇到跨域问题。

我知道跨域问题是 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/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(使用 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=$1
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>
# END WordPress

wordpress/wp-content/themes/twentyone/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();
        }
    }
}

我做了一个安静的 api 日志,当邮递员成功创建它是请求“POST”但这个总是作为“GET”发送并且即使我确定是我发送的帖子也无法创建。我尝试将 nginx 放在允许来源“*”上,也尝试直接放入 apcache 服务器,但它们都不起作用,被卡住了 3 天,我不知道如何解决这个问题,如果有人在查看后得到一些好的建议在代码中,请与我分享,将是伟大的。

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

【问题讨论】:

  • 您在 .htaccess 中检测 OPTIONS 的尝试可能为时已晚 - 除非请求是针对物理上存在的文件或文件夹,否则 RewriteRule . /index.php [L] 将已经重写它,并且 L 标志在之后结束处理那个。
  • if ( $origin == 'http://localhost:3000/' ) - 我认为原点末尾没有斜杠。
  • @CBroe 我之前也删除了斜线,同样的,你的意思是我应该在 /index.php [L] 之前调用 RewriteCond %{REQUEST_METHOD} OPTIONS [L]
  • 是的,它需要在此之前才能生效。
  • @CBroe 我切换了 RewriteRule 。 /index.php [L] 到 {REQUEST_METHOD} 选项的顶部,wordpress 前端有一些奇怪的行为,也根本不起作用。

标签: wordpress .htaccess cors nuxt.js woocommerce-rest-api


【解决方案1】:

wordpress/wp-content/themes/你的wordpress选择的主题/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 以及 if 'POST' == $_SERVER['REQUEST_METHOD'] 上是否有任何 'POST 或 'PUT' 切换到 '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 发送任何标头,在 js 部分删除数据对象,不知何故 woocommerce rest api 在没有对象数据包装的情况下接受。

nuxt.js/plugins/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);
    }

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
  • 2016-02-12
  • 2011-05-04
  • 2021-05-07
  • 2022-07-11
  • 1970-01-01
相关资源
最近更新 更多