我正在測驗從前端發布資料到后端 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/主題/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();
}
}
}
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
uj5u.com熱心網友回復:
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/插件/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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411227.html
標籤:
