【发布时间】: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