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

如何在JS的Fetch POST请求后保存请求体?

解决方案:Fetch POST 请求完成后保存请求体

你要保存的是发送给服务器的请求体数据(即代码里的objectUser或原始user对象),可以在请求完成的回调中通过两种常用方式存储:

1. 内存临时存储(页面刷新后丢失)

在合适的作用域声明变量,请求完成后将请求体赋值给它:

// 定义变量存储请求体,可根据需求调整作用域
let savedRequestBody;

async function connectUser () {
    const log = document.querySelector("#formulaireConnexion")
    log.addEventListener("submit", function(event){
        event.preventDefault()

        const user = {
            email: event.target.querySelector("[name=mail]").value,
            password: event.target.querySelector("[name=mdp]").value
        }

        const objectUser = JSON.stringify(user)

        fetch("http://localhost:5678/api/users/login", {
            method: "POST",
            headers: {"Content-Type" : "application/json"},
            body: objectUser
        })
        .then(r => r.json())
        .then(body => {
            console.log(body);
            // 请求完成后保存序列化后的请求体
            savedRequestBody = objectUser;
            // 若要保存未序列化的原始对象,改为:savedRequestBody = user;
        })
        .catch(err => console.error('请求出错:', err));
    })
}

connectUser()

后续可直接通过savedRequestBody调用保存的数据。

2. 本地持久化存储(页面刷新后仍保留)

如果需要长期保存,使用localStorage或sessionStorage:

async function connectUser () {
    const log = document.querySelector("#formulaireConnexion")
    log.addEventListener("submit", function(event){
        event.preventDefault()

        const user = {
            email: event.target.querySelector("[name=mail]").value,
            password: event.target.querySelector("[name=mdp]").value
        }

        const objectUser = JSON.stringify(user)

        fetch("http://localhost:5678/api/users/login", {
            method: "POST",
            headers: {"Content-Type" : "application/json"},
            body: objectUser
        })
        .then(r => r.json())
        .then(body => {
            console.log(body);
            // 用localStorage持久化保存,自定义存储key
            localStorage.setItem('lastLoginRequestBody', objectUser);
            // 若保存原始对象,需先序列化:
            // localStorage.setItem('lastLoginUser', JSON.stringify(user));
        })
        .catch(err => console.error('请求出错:', err));
    })
}

connectUser()

读取时使用localStorage.getItem('lastLoginRequestBody'),若保存的是原始对象,需解析:JSON.parse(localStorage.getItem('lastLoginUser'))。

⚠️ 注意:密码属于敏感数据,不建议存入本地存储,存在内存中更安全(页面关闭即清除)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:55:46