【问题标题】:Changing json on express node.js server在 express node.js 服务器上更改 json
【发布时间】:2017-09-10 04:59:51
【问题描述】:

总的来说,我对 node.js 和 Web 开发还很陌生(所以,如果我完全不了解基础并且你有很好的材料供我使用,我真的很想看到它)。

我正在尝试在 node.js 服务器和 http 客户端之间来回传递 JSON 对象的原型。到目前为止,客户端看起来像:

<script type="text/javascript">
document.getElementById("myBtn").addEventListener("click", passArg);

function passArg() {
    console.log("I'm here")
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.open("POST", "/", true);
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
                //var json = JSON.parse(xmlhttp.responseText);      
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    }

    var data = JSON.stringify({"email":"hey@mail.com","password":"101010"});    
    xmlhttp.send(data);
    get_json(); 
}

function get_json(){
    console.log("getting json");
    var xmh = new XMLHttpRequest();

    xmh.open("GET", "/playlist/playlist.json", true);
    xmh.send();

    xmh.onreadystatechange = function() {
        if (this.readyState == this.DONE ) {
           if (this.status == 200) {
                var json = JSON.parse( this.responseText );
                console.log(json.email + " "+ json.password + " " + json.access_date); 
           }
           else if (xmh.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    }


}
</script>

而服务端编码为

app.post("/", function (req, res) {
    console.log('Request received');

    req.on('data', function (chunk) {
        console.log('GOT DATA!');
        json = JSON.parse(chunk);
        json.access_date  =  "12.04.17";

        write_json(json)
        console.log("finished writing- in app_post")
    });

    console.log("passing all clear to client")
    res.writeHead(200);

    res.send();

})

function write_json(chunk){
    console.log("WHADDUP")
    console.log(JSON.stringify(chunk))
    fs = require("fs")
    var filename = "./public/playlist/playlist.json";
    var file = require(filename);

    file = chunk;

    fs.writeFile(filename, JSON.stringify(file), function(err){  
        if (err) return console.log(err);
            console.log(JSON.stringify(file));
            console.log('writing to ' + fileName);
        }
    )
    console.log("finished writing - in write_json")
    }

在服务器端控制台上生成以下输出

Request received
passing all clear to client
GOT DATA!
WHADDUP
{"email":"hey@mail.com","password":"101010","access_date":"12.04.17"}
module.js:428
    throw err;
    ^

SyntaxError: public/playlist/playlist.json: Unexpected end of input

在客户端读取的东西是控制台

(index):15 I'm here
(index):41 getting json
(index):45 GET http://localhost:8080/playlist/playlist.json net::ERR_CONNECTION_RESET

从这里我读到异步 POST 事件在文件本身更新之前发送所有清除调用get_json。而且似乎服务器端文件的更新也不能正常工作。如何构建调用以使编辑非常顺畅?

【问题讨论】:

    标签: javascript json node.js express xmlhttprequest


    【解决方案1】:

    快速的答案是创建一个函数来调用 res.send,将它传递给您的 write_json 函数,然后从您的 writeFile 回调中调用它。

    app.post("/", function (req, res) {
        console.log('Request received');
    
        req.on('data', function (chunk) {
            ...
    
            write_json(json, function() {
                console.log("passing all clear to client")
                res.writeHead(200);
    
                res.send();
                console.log("finished writing")
            });            
        });    
    });
    
    function write_json(chunk, onFinishedWriting){
        ...
        fs.writeFile(filename, JSON.stringify(file), function(err){  
            if (err) {
                 return console.log(err);                
            }
            else {
                console.log(JSON.stringify(file));
                console.log('writing to ' + fileName);
                onFinishedWriting();
            }
       });
    
    }
    

    但是当你发现自己在编写这样的代码时:

             });
         });
     });
    

    那么您可能处于众所周知的“回调地狱”中。我怀疑你想要的是使用承诺。 Here's a question specifically about promises and writeFile 这可能会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 2018-07-17
      • 2018-01-12
      • 2020-05-29
      • 2016-01-18
      • 2018-05-15
      相关资源
      最近更新 更多