fetch - 来自 DOM 的代理 webpack-dev-server
问题描述
我想index.html
在本地应用程序的初始加载中添加 fetch 调用。否则,此数据会在服务器端加载,但对于这种特殊情况,我需要在 dev 中进行 http 调用。
我在将 fetch 添加到 DOM 的情况下代理 webpack-dev-server 时遇到了困难。
在我的应用程序被实例化并且我使用 Axios对/api
.
这让我有点困惑——为什么代理可以在 JS 加载后工作,但不能在 init 上工作?
devServer: {
contentBase: '/some/path',
port: 9000,
https: true,
open: true,
compress: true,
hot: true,
proxy: { '/api/*': [Object] }
},
索引中的脚本
<script>
(async function() {
const data = await getData();
addDataset(data);
async function getData() {
return fetch('/api/my/endpoint').then(
(response) => response.data.result,
);
}
function addDataset(data) {
var el = document.getElementById('root');
const parsed = JSON.parse(data);
Object.entries(parsed).forEach((entry) => {
const [k, val] = entry;
el.dataset[k] = JSON.stringify(val);
});
}
})();
</script>
错误
400 Bad request
Request URL - https://localhost:9000/api/my/endpoint
解决方案
推荐阅读
- javascript - useEffect 挂钩从返回承诺的函数更新状态
- reactjs - react-icons - 无法更改颜色垫圈图标
- ios - 更改约束后恢复 UIView 的 NSLayoutConstraint
- c++ - 部分递归调用mergeSort期间合并排序的无限循环问题
- css - CSS 标签:悬停~ .colaOutside .straw { 变换:旋转(15度);我希望当我将鼠标悬停在稻草上时可以移动度数。但它不工作
- python - Web 服务使用 python 查找股票的收盘价
- javascript - 如何将锚标记居中在其父级用作叠加层的 div 内
- python - 使用python脚本将对象链接到搅拌机关键帧处的父级
- pandas - 无法将数据框转换为镶木地板,TypeError
- python - Airflow - xcom 返回最后一个带逗号的值