首页 > 解决方案 > 当我更改 Axios 参数时,前端:8080 提交到后端:80 中断

问题描述

我正在构建一个主要用于学习 Vue (Vue3) 的应用程序。

前端8080端口使用axios提交到后端80端口。

这是我的vue.config.js

module.exports = {
  devServer: {
    host: 'myste.com',
    public: 'myste.com:8080',
    proxy: {
      "/fn/*": {
        target: "http://myste.com",
        // because changeOrigin is true, and port 80 is the default, I don't need to include it here.
        changeOrigin: true,
        pathRewrite: {
            '^/fn': ''
        }
      }
    }
  }
}

文档说用 data 属性发送数据

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

这就是我在我的 Vue3 应用程序中所做的

this.$http({
    method: 'post',
    url: e.target.action,
    data: {toEmail: document.querySelector('.toEmail').value}
});

这会导致调用正确的 url ( myste.com/handler.php),根据proxy设置进行修改,但不会发送任何数据。我的后端报告缺少第一个参数。

如果我将“数据”更改为参数

this.$http({
    method: 'post',
    url: e.target.action,
    params: {toEmail: document.querySelector('.toEmail').value}
});

它提交了所有数据,但提交到了错误的 url ( myste.com:8080/fn/handler.php?toEmail=...)。

我已经来回改变了好几次,这个属性就是我要改变的所有东西,以便发生这种奇怪的事情。

标签: vue.jsvuejs3

解决方案


在 github 讨论中找到了一种解决方法,它使事情变得非常简单,并且data.我仍然有兴趣知道这里的问题是什么以及如何解决它。

import { createApp } from 'vue'
import App from './App.vue'

import router from './router'

import axios from 'axios'
import VueAxios from 'vue-axios'

axios.interceptors.request.use((config) => {
    if (config.headers['Content-Type'] && config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.transformRequest = (data) => {
        const str = [];
        Object.keys(data).forEach(key => str.push(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`));
        return str.join('&');
      };
    }

    return config;
  }, error => Promise.reject(error));

this.$http现在的调用看起来像这样,添加了内容类型。

    this.$http({
        method: 'post',
        url: e.target.action,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        data: {...}
      })

推荐阅读