【问题标题】:Function is returning curly braces函数返回花括号
【发布时间】:2021-10-10 08:09:01
【问题描述】:

我之前问过非常相似的问题 (Why is it when posting an object into a json file, one of the key/value always appears as curly braces?),我讨厌再问一次,但我在任何地方都找不到答案。 所以我有这个返回“hello”的函数(它应该返回一个特定的值,但无论哪种方式都会发生错误,所以我有“hello”进行测试)。

function index(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            $("#noteDisplay").on("click", ".remove", (e) => {
                //indexResult = (e.currentTarget.parentNode.id - 1);
                const indexResult = "hello";
                let error = false;
                //-----
                if(!error){
                    resolve(indexResult);
                } else {
                    reject('Something went wrong!');
                }
            });
        }, 2000);
    });
}      

我在这里调用这个函数。

export default function SendId(){
    React.useEffect(() => {
        /*$("#noteDisplay").on("click", ".remove", async (e) => {
            console.log("ola");
        });*/
        //-----------------------------------------------------
        $("#noteDisplay").on("click", ".remove", async (e) => {
            const PORT = process.env.PORT || 3001;
        
            let index_note = { // the object
                index: await index()
            }
        
            let data = JSON.stringify(index_note);
        
            let xhr = new XMLHttpRequest();
            xhr.open('POST', `http://localhost:${PORT}/api/1`, true);
            xhr.send(data);
            console.log("the data was sent")
        });
        
    });
    return(null);
}

无论有没有异步等待,当我记录它时,它总是会重新调整花括号。 我以这种方式控制台记录它(但我认为这不是问题)。

app.post("/api/:1", (req, res) =>{
  console.log(req.body);
});

对于重复的问题,我们深表歉意,我们将不胜感激。

【问题讨论】:

  • 您的问题是关于 JavaScript,而不是 Java,这是一种完全不同的编程语言。我已经为您更改了问题的标签,因为吸引错误的专家来回答您的问题是没有意义的。

标签: javascript reactjs async-await


【解决方案1】:

您没有将 'Content-Type': 'application/json' 添加到您的请求标头中。也许这是个问题

xhr.setRequestHeader('Content-Type', 'application/json');

【讨论】:

    猜你喜欢
    • 2020-07-17
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多