【发布时间】:2020-10-28 18:31:51
【问题描述】:
我正在开发一个新的 VueJS 应用程序,它通过 axios 访问一个用 PHP 构建的简单 API 端点。我已将 PHP 端点代码剥离为简单的回显,以排除其他导致问题的代码:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Api-Token");
echo 'hello';
目前,开发正在本地开发主机名上运行:
- vueJS 应用程序-http://app.livechat.local:8000/
- PHP API - http://api.livechat.local/
在我的应用程序中,我正在做一个简单的拦截器来附加一个自定义标头“X-Api-Token”,我最终将在端点上对其进行验证。
import Vue from 'vue';
import vuetify from "./vuetify";
import axios from "axios";
import VueRouter from "vue-router";
import App from './App.vue';
import VueSocketIOExt from "vue-socket.io-extended";
import io from "socket.io-client";
import routes from "./routes";
import './style.scss';
const socket = io(SOCKET_URL);
// axios config
axios.defaults.baseURL = API_URL;
axios.interceptors.request.use(function (config) {
config.headers = {
'X-Api-Token': 'test'
};
return config;
});
Vue.use(VueSocketIOExt, socket, vuetify, axios);
Vue.use(VueRouter);
const router = new VueRouter({routes});
Vue.prototype.$http = axios;
Notification.requestPermission();
router.beforeEach((to, from, next) => {
console.log(to.name);
if(to.name !== 'login' && to.name !== 'register' && to.name !== 'logout' && to.name !== 'forgot-password') {
axios.get('/',{
params: {
endpoint: 'agentCheckSession'
}
})
.then(response => {
console.log(response);
});
} else {
next();
}
});
new Vue({
el: '#app',
router,
vuetify,
render: h => h(App)
});
但是,当我添加自定义标头时,CORS 会响应:
访问 XMLHttpRequest 在 来自原点的“http://api.livechat.local/?endpoint=agentCheckSession” 'http://app.livechat.local:8000' 已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
如果我从 axios 拦截器中删除自定义标头,它会毫无问题地继续进行。
我已通过在浏览器中访问 PHP 脚本来确认它是有效的。
这里是开发工具检查:
如何成功传递自定义标头?我正在寻找一种在 PHP 和/或 JS 中解决此问题的有效方法,因此我不是在寻找代理或“在 chrome 中禁用”解决方案。
【问题讨论】:
-
我发现“简单请求”不允许自定义标头...这很奇怪,因为我可以使用 jQuery 的 Ajax() 发送自定义标头。 developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
标签: php vue.js vuejs2 axios cors