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

访问localhost:8383/info时浏览器显示JSON而非HTML,如何实现视频效果?

问题

我跟着视频操作时,看到视频中向localhost:8383/info发送GET请求,Network面板能看到返回的JSON {info: "Text"},但浏览器依然展示HTML页面;而我直接在地址栏输入相同地址时,浏览器直接显示该JSON而非HTML页面。请问如何实现视频中的效果?

另外,我访问localhost:8383(不带info)时,返回的是HTML文件,这是正常的,但我想搞清楚怎么做到视频里那种请求后不跳转页面的效果。

我的代码

Index.html(位于public文件夹)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="">
        <input id="input" type="text">
        <button id="get">Get</button>
    </form>
</body>
<script>
    const input = document.getElementById("input")
    const getbtn = document.getElementById("get")

    getbtn.addEventListener("click", getInfo);

    async function getInfo(e) {
        e.preventDefault()
        const res = await fetch("http://localhost:8383/info", {method: "GET"})
        console.log(res)
    }
</script>
</html>

Server.js

const express = require("express")
const app = express()
const port = 8383

app.use(express.static("public"))

app.get("/info", (req, res) => {
    res.status(200).json({info: "Text"})
})

app.listen(port, () => console.log("Server started")) 
解决方案

关键区别在于请求的发起方式:

  1. 视频中的请求是通过页面内的JavaScript(也就是你代码里的fetch)发起的AJAX请求,这种请求在后台异步发送,不会触发浏览器页面跳转或刷新,所以浏览器会一直展示原来的HTML页面,同时Network面板能捕获到请求和返回的JSON数据。
  2. 你直接在地址栏输入localhost:8383/info时,是浏览器主动向服务器发起页面请求,服务器返回JSON后,浏览器会默认展示这个JSON内容,这是正常的浏览器行为。

要实现视频中的效果,按以下步骤操作即可:

  • 启动Express服务器(运行node Server.js)
  • 在浏览器地址栏输入localhost:8383,加载你的HTML页面
  • 点击页面上的Get按钮,此时打开浏览器开发者工具的Network面板,就能看到/info请求返回的JSON,同时浏览器依然停留在当前HTML页面,和视频中的效果完全一致。

你当前的代码已经完全具备实现这个效果的能力,只是之前用了错误的请求发起方式(地址栏直接输入),而非页面内的按钮触发AJAX请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:00:56