You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iPhone通过电脑热点连接本地主机时网页无法加载API请求

问题解决:手机通过热点访问本地Web应用时前端无法加载API请求

核心问题

前端代码硬编码了API请求地址为http://localhost:4545/items,在iPhone上访问时,localhost指向的是手机自身而非运行后端的电脑,导致请求无法发送到正确的服务器。这也是你直接在手机访问服务器API(用电脑IP)能正常工作,但前端页面里的请求失败的原因。

解决方案

1. 修改前端API请求为相对路径(推荐)

将JavaScript中的fetch地址改为相对路径,页面会自动使用当前加载页面的域名/IP发起请求,无需硬编码地址:

修改后的index.js:

async function loadData() {
    try {
        // 替换绝对路径为相对路径
        const res = await fetch("/items")
        const data = await res.json()
        if (!res.ok) {
            console.log("请求异常")
            return
        }
        const itemsContainer = document.getElementById("itemsContainer")
        data.forEach(element => {
            const itemDiv = document.createElement("DIV")
            itemDiv.className = "auction-item"
            const previousBids = element.previousBids
            let previousBidsText = ""
            for (let i = 0; i < previousBids.length; i++) {
                previousBidsText += `$${previousBids[i]}, `
            }

            itemDiv.innerHTML = `    
        <h2>${element.name}<img src="${element.image}" class = "preview"></h2>
        <p>Category: ${element.category}</p>
        <p>Seller: ${element.seller}</p>
        <p>Description: ${element.description}</p>
        <p>Current Bid: $${element.highestBid}</p>
        <p>Last 3 Bids: ${previousBidsText}</p>
        <p>Bidding ends in: ${element.endTime}</p>
        
        <button class="bid-button">Bid Now</button>
        `
            itemsContainer.appendChild(itemDiv)
        });
    } catch (error) {
        console.log(error)
    }
}

2. 确保后端服务器监听所有网络接口

默认情况下,Express的app.listen只监听localhost(127.0.0.1),局域网内其他设备无法访问。修改为监听0.0.0.0,让服务器接收来自所有网络接口的请求:

修改后端代码中的listen部分:

// 启动express服务器,监听所有网络接口
app.listen(4545, '0.0.0.0', ()=>{
    console.log("服务器已启动,监听端口4545")
})

3. (可选)用电脑局域网IP替换localhost

如果不想用相对路径,可以把前端fetch的localhost换成电脑在热点下的局域网IP(比如192.168.1.100,具体IP可在电脑的网络设置中查看):

const res = await fetch("http://192.168.1.100:4545/items")

额外验证步骤

  • 确认电脑和iPhone连接同一个热点
  • 关闭电脑防火墙(或允许4545端口的入站请求)
  • 在iPhone浏览器中直接访问http://[电脑IP]:4545/items,确认API能返回数据

内容的提问来源于stack exchange,提问作者ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 13:04:50