首页 > 解决方案 > Vue.js - vue.config.js 中的代理被忽略

问题描述

我一直在搜索和阅读有关此主题的文档,但我无法让它发挥作用。 https://cli.vuejs.org/config/#devserver-proxy

我通过命令正常地制作了我的 Vue.js 应用程序

vue create my-app

所以我通过命令运行应用程序

npm run serve

http://localhost:8080/上。相当标准的东西。

但是我的应用程序需要一个在https://localhost/上运行的 PHP 后端, 所以我在根目录的 vue.confic.js 文件中设置了代理设置。

vue.confic.js 文件内容:

module.exports = {
    devServer: {
        proxy: {
            '^/api': {
                target: 'https://localhost/',
                ws: true,
                changeOrigin: true
            }
        }
    }
};

我正在尝试让 axios 调用地址上的脚本

https://localhost/test.php

axios 调用是

mounted() {
    this.$axios.get('api/test.php', {})
        .then(response => { console.log(response.data) })
        .catch(error => { console.log(error) });
    },

但由于某种原因,我无法弄清楚我仍然得到

GET http://localhost:8080/api/test.php 404 (Not Found)

先感谢您。我会很高兴任何提示。

标签: vue.jsproxy

解决方案


您的 axios 调用将使用网页使用的任何协议向 API 发出请求。

该错误表明您正在进行 http 调用,但您的 webpack 配置只是欺骗 https。您是从发出请求的页面访问 https 吗?

例如https://localhost:8080

您也可以尝试更新您的 webpack 代理服务器,使其看起来像这样

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'https://other-server.example.com',
        secure: false
      }
    }
  }
};

其他调试步骤:从终端卷曲您的 Api 端点以查看是否是协议问题


推荐阅读