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

手机访问本地服务器按钮点击后search()函数未执行问题求助

问题

  • PC端通过localhost访问网站正常运行
  • 手机通过IP访问localhost可获取客户端的HTML、CSS和JS资源
  • 点击按钮后能添加“hi”,但search()函数未执行
  • 直接输入http://localhost:3000/users可获取“hi1”

客户端代码

const button = document.querySelector("button");

button.addEventListener("click", () => {
    document.getElementById("imageDiv").innerHTML = "Hi";//this work   
    search();//this not work
});

async function search(){
    await fetch("http://localhost:3000/users")
    .then(response => response.json())
    .then(response => {
        var image;   
        image = JSON.parse(JSON.stringify(Object.assign({},response)));
        document.getElementById("imageDiv").innerHTML = response;
    })};

服务端代码

const express = require('express');
const bodyParser = require('body-parser');
const path = require("path"); // window or mac
const cors = require('cors');
const app = express();
const port = 3000;
//var word = "";
//const router = express.Router();


// configure CORS to avoid CORS errors
app.use(cors());

// configure body parser so we can read req.body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static('./client'));

app.get('/', (req, res) => {
    res.sendFile("./index.html");
});


app.get("/users", (req, res) => {  
    datafiles = ["hi1"];
    res.json(datafiles);
    res.status(200);
});


app.listen(port, () => {
    console.log(`Server listening on http://localhost:${port}`);
});

解决方案

1. 修复fetch的硬编码域名问题

手机通过IP访问时,客户端代码里的fetch("http://localhost:3000/users")会尝试请求手机本地的3000端口,而非你的PC服务器。把请求地址改成相对路径,自动适配当前访问的域名/IP:

await fetch("/users")

2. 添加错误捕获排查问题

search()函数没有错误处理逻辑,请求失败时无法定位问题。给fetch添加catch块,同时校验响应状态:

async function search(){
    await fetch("/users")
    .then(response => {
        if (!response.ok) {
            throw new Error(`请求失败,状态码:${response.status}`);
        }
        return response.json();
    })
    .then(response => {
        // 直接将数组转字符串显示,去掉冗余的JSON操作
        document.getElementById("imageDiv").innerHTML = response.join(', ');
    })
    .catch(error => {
        console.error('请求出错:', error);
        document.getElementById("imageDiv").innerHTML = '加载失败:' + error.message;
    });
}

3. 修复服务端sendFile路径问题

服务端res.sendFile("./index.html")的相对路径可能因运行目录解析错误,改用绝对路径确保文件能被正确找到:

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, './client/index.html'));
});

4. 修改服务端监听地址

默认express仅监听localhost,手机无法通过IP访问。修改listen参数让服务器监听所有网卡:

app.listen(port, '0.0.0.0', () => {
    console.log(`Server listening on http://0.0.0.0:${port}`);
    console.log(`本地访问:http://localhost:${port}`);
    console.log(`手机访问:http://[你的PC局域网IP]:${port}`);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:20:31