Search code examples
javascriptnode.jsexpressxmlhttprequest

response.send in express.js is sending response to xhr but responseText in xhr is null


I wanna make a get request from my client. to read a file and give me as response. I'm using xhr to do that. A request will be sent each 1 second. All the requests are in an array named XHRS.Here is what am i talking about : `

var XHRS = [];
var i = 0;
SendRequest();
function SendRequest() {
    XHRS[i] = new XMLHttpRequest();
    XHRS[i].onload = function(){
        var ChatData = XHRS[i].responseText.split("\n");
        document.getElementById("ServerMessages").innerHTML = "";
        for (var j in ChatData) {
            var parent = document.getElementById("ServerMessages");
            var el = document.createElement("li");
            el.textContext = ChatData[j];
            parent.appendChild(el);
        }
        debugger;
        i++;
        setTimeout(SendRequest, 1000);
    }
    XHRS[i].open("GET", "/read?url=messages.txt", false);
    XHRS[i].send();
}

as you can see here. I used i to split the requests. And i used onload to see if sending request is done. In the server i get the request like this :

app.get('/read', function(request, response) {
    console.log("readFileUrl : " + request.query.url);
    response.type("html");
    response.send(getReadFile(request.query.url));
});
function getReadFile(url){
    var Data;
    readFile(url);
    async function readFile(filePath) {
        try {
          var data = await fs.readFile(filePath);
          Data = data;
          console.log(data.toString());
        } catch (error) {
          console.error(`Got an error trying to read the file: ${error.message}`);
        }
    }
    return Data;
}

` My problem is that responseText is null. While i sent the response in the server. I checked if the getReadFile returns null but it had the text. What should i do?
The interesting thing is that it will get an error while i use response.write and then response.end. it gets this error :

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
    at new NodeError (node:internal/errors:371:5)
    at write_ (node:_http_outgoing:742:11)
    at ServerResponse.write (node:_http_outgoing:707:15)
    at E:\alireza\vscode programs\node.js chat without socket.io\index.js:11:14
    at Layer.handle [as handle_request] (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\layer.js:95:5)
    at E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\index.js:346:12)
wfveragerfgesgerg
readFileUrl : messages.txt
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
    at new NodeError (node:internal/errors:371:5)
    at write_ (node:_http_outgoing:742:11)
    at ServerResponse.write (node:_http_outgoing:707:15)
    at E:\alireza\vscode programs\node.js chat without socket.io\index.js:11:14
    at Layer.handle [as handle_request] (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\layer.js:95:5)
    at E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (E:\alireza\vscode programs\node.js chat without socket.io\node_modules\express\lib\router\index.js:346:12) 

Solution

  • I think you forget to put the await/async part to your function

    app.get('/read', async function(request, response) {
        console.log("readFileUrl : " + request.query.url);
        response.type("html");
        response.send(await getReadFile(request.query.url));
    });
    async function getReadFile(url){
        var Data;
        await readFile(url);
        async function readFile(filePath) {
            try {
              var data = await fs.readFile(filePath);
              Data = data;
              console.log(data.toString());
            } catch (error) {
              console.error(`Got an error trying to read the file: ${error.message}`);
            }
        }
        return Data;
    }
    

    and you can just do it simply:

    app.get('/read', function(request, response) {
        console.log("readFileUrl : " + request.query.url);
        response.type("html");
        response.send(fs.readFileSync(request.query.url));
    });