javascript - 具有特定/不同端口的 window.fetch
问题描述
请考虑以下代码,其中在fetch
调用中指定了相对 URL。这适用于默认端口。
let url = '/api/send'
let response = await window.fetch(url, {
method: 'POST'
});
除非指定完整的window.fetch
URL,否则不允许指定端口,如下所示。
let url = 'http://<some_url>:<some_port>/api/send'
let response = await window.fetch(url, {
method: 'POST'
});
有没有办法为获取调用动态更改端口?
解决方案
您可以使用window.location.origin
访问当前 url,然后连接端口和路径。
它看起来像这样:
let domain = window.location.origin; //http://someurl.com
let port = 8080;
let url = `${domain}:${port}/api/send`;
let response = await window.fetch(url, {
method: 'POST'
});
推荐阅读
- java - 如何在java中将后退导航图标添加到appBarLayout
- c# - 使用 WasapiOut Naudio 更改声卡的采样率
- jquery - 在自定义 Angular 6+ 库中使用 jQuery
- python - 是否有一个 pandas/numpy 函数可以将一个整数分布在后续的零上?
- php - SyntaxHighlighter Evolved:PHP 版本 >7.0 无法正常工作
- r - 叠加正态分布图
- jenkins - 从 Jenkins Subversion 插件中获取已删除的 SVN 存储库
- wordpress - 在多站点 wordpress nginx 服务器中更改永久链接后,帖子链接转到 404
- reactjs - 使用 TypeScript 在 React 中键入动态标签?
- python - 无法在 Google Colaboratory 上升级 pyzmq