简体   繁体   English

在AJAX和Node.js中使用发布请求时,将结果保存在JSON文件中

[英]Save the result in JSON file when using post request in AJAX and Node.js

Now I am writing an javascript to track the system configuration of users eg screen resolution statistic. 现在,我正在编写一个JavaScript来跟踪用户的系统配置,例如屏幕分辨率统计信息。 I first wrote the AJAX file to collection in object form and use node.js to take the request and finally write the input into the json file in server side. 我首先将AJAX文件以对象形式编写为集合,并使用node.js接收请求,最后将输入写入服务器端的json文件中。

My AJAX code is as follows: 我的AJAX代码如下:

  try{

  window.onload = function(url, callback, data, x) {
  var sWidth = screen.width;
  var sHeight = screen.height;
  var sColor = screen.colorDepth;
  var sPlatform = window.navigator.platform;
  var sLanguage = navigator.language;
  var sTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

  var info = {
    width: sWidth,
    height: sHeight,
    color: sColor,
    platform: sPlatform,
    language: sLanguage,
    timezone: sTimeZone
  };

    //var http = new XMLHttpRequest();
    var http = new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');

    http.onreadystatechange = function () {
      if (http.readyState == 4 && http.status == 200) {
        console.log(JSON.parse(http.response));
      }
    };

    http.open("POST", "http://127.0.0.1:8080/ReturnFingerprint.json", true);
    http.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    http.setRequestHeader("Content", "application/x-www-form-urlencoded")
    http.send(info);
  }
} catch (e) {
  console.log(e);
}

And the following Node.js code to take over the AJAX request 下面的Node.js代码接管AJAX请求

var express = require('express');
var bodyParser = require('body-parser');
var app= express();
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(bodyParser.json());
app.options('/Fingerprint', cors()) ;

app.post('/Fingerprint', urlencodedParser, function(req, res, next) {
  if (!req.body) {
    var json = JSON.stringify(req.body);
    var fs = require('fs');
    fs.readFile('ReturnFingerprint.json', 'utf8', function readFileCallback(err, data){
    if (err){
        console.log(err);
        next(err)
    } else {
      data = JSON.parse(data);
      json = JSON.stringify(data);
      fs.writeFile('ReturnFingerprint.json', json, 'utf8', function writeFilecallback (err, data) {
        res.json(json)});
      });
    }
  }
  res.json(json);
});

When I checked the json file, there is nth updated. 当我检查json文件时,第n次更新。

And when I inspected the network element in google chrome, it returns that the ReturnFingerprint.json is pending and no more error message or detail is provided. 当我检查google chrome中的网络元素时,它返回ReturnFingerprint.json处于待处理状态,并且不再提供错误消息或详细信息。

What is the error of the code?Many thanks for your help in advance. 代码有什么错误?非常感谢您的提前帮助。

You need to tell Express that you're done with handling of the request eg. 您需要告诉Express,例如,您已经完成了处理请求的工作。 by res.send('hello') or res.json(jsonObject) . 通过res.send('hello')res.json(jsonObject) You should call it in the writeFile callback. 您应该在writeFile回调中调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM