0
我对node.js和web开发一般都很陌生(所以如果我完全没有基础,并且你有很好的材料供我使用,我真的很希望看到它)。在express上更改json node.js服务器
我试着在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":"[email protected]","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":"[email protected]","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
。而且似乎在服务器端的文件更新不起作用。如何构建调用以使编辑非常流畅?