简体   繁体   English

对node.js服务器的AJAX调用返回未定义

[英]AJAX call to node.js server returns undefined

I am trying to access a string that is returned by a serverside Node.js function. 我正在尝试访问服务器端Node.js函数返回的字符串。

function createString () {
    do something ...
    console.log(finalString);
    return finalString;
};

I am using a plain JavaScript AJAX request to GET the string from the server 我正在使用普通的JavaScript AJAX请求从服务器获取字符串

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    do something ...
};
xhr.open('GET', 'http://localhost:5000/array');
xhr.send();

My serverside looks like: 我的服务器端看起来像:

app.get('/array', (req, res) => {
        console.log('request received');
        console.log(createString());
        res.send(createString());
    }
);

createString() is always returning as 'undefined' for the AJAX request even though it is logging the correct string in finalString. 对于AJAX请求,尽管createString()始终在finalString中记录正确的字符串,但始终返回“ undefined”。

I believe the issue is the asynchronous aspect of AJAX but I am not sure how to tell res.send() to wait until createString() runs . 我相信问题是AJAX的异步方面,但是我不确定如何告诉res.send()等待createString()运行

Any help is appreciated! 任何帮助表示赞赏!

You can pass the req and res objects to your createString function. 您可以将reqres对象传递给createString函数。 (I am assuming that your createArray is a typo, and should be createString ). (我假设您的createArray是一个错字,应该是createString )。 Indeed if you have just this function, you can simply have: 确实,如果您仅具有此功能,则可以简单地拥有:

server.js server.js

app.get('/array', createString);

createString.js createString.js

function createString (req, res) {
    do something ...
    console.log(finalString);
    return res.status(200).send(finalString);
};

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

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