vue.js - 当我更改 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=...
)。
我已经来回改变了好几次,这个属性就是我要改变的所有东西,以便发生这种奇怪的事情。
解决方案
我在 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: {...}
})
推荐阅读
- python - Python - 比较两个列表,卡在try catch
- json - Logstash 使用 JSON 字段日期而不是 @timestamp
- css - 事件弹出窗口在日历网格和数字后面绘制
- javascript - JavaScript 和 jQuery 中的错误
- python - Droplets 和 Django 中的 URL 问题
- zipkin - 密码保护zipkin
- sql - 在 LIKE 中转义通配符
- python-hypothesis - 使用 pytest.raises 的假设状态测试不报告步骤顺序
- linux - shm_open 未设置组写访问权限
- asp.net - asp:Updatepanel,更新面板出现问题,因为每次单击按钮时我的页面都会进行完整的回发