首页 > 解决方案 > 具有特定/不同端口的 window.fetch

问题描述

请考虑以下代码,其中在fetch调用中指定了相对 URL。这适用于默认端口。

let url = '/api/send'
let response = await window.fetch(url, {
   method: 'POST'
});

除非指定完整的window.fetchURL,否则不允许指定端口,如下所示。

let url = 'http://<some_url>:<some_port>/api/send'
let response = await window.fetch(url, {
   method: 'POST'
});

有没有办法为获取调用动态更改端口?

标签: javascriptfetch-api

解决方案


您可以使用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'
});

推荐阅读