【问题标题】:Axios GET request to PHP API not working with custom header对 PHP API 的 Axios GET 请求不适用于自定义标头
【发布时间】: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';

目前,开发正在本地开发主机名上运行:

在我的应用程序中,我正在做一个简单的拦截器来附加一个自定义标头“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 中禁用”解决方案。

【问题讨论】:

标签: php vue.js vuejs2 axios cors


【解决方案1】:

我认为在这部分:

axios.interceptors.request.use(function (config) {
    config.headers = {
        'X-Api-Token': 'test'
    };
    return config;
});

您正在覆盖请求的所有标头。尝试将您的标题添加到标题中而不是覆盖它们,例如:

axios.interceptors.request.use(function (config) {
    config.headers.token = "test";
    return config;
});

【讨论】:

  • 我试过了,它也不起作用。我还确保在后端反映“令牌”名称,仍然是同样的问题。
猜你喜欢
  • 2019-04-11
  • 2020-06-13
  • 2017-06-20
  • 2020-07-19
  • 2018-10-12
  • 2017-12-04
  • 2018-07-01
  • 2021-05-11
  • 2016-11-12
相关资源
最近更新 更多