res.json在回调函数内部无效

时间:2016-01-16 07:50:56

标签: javascript node.js express

我目前正在使用API​​端点。

将数据发布到端点/authenticate后,我使用plaidClient.getAuthUser功能获取用户的帐户信息,然后我尝试使用{{1} }返回帐户数据。

运行之后:

res.json

我成功地看到了包含帐户信息的字典数组。

但是,当我尝试使用accounts = JSON.stringify(res.accounts); console.log('accounts: ' + accounts); 时,我收到错误:

res.json({accounts: accounts})

当我尝试运行 res.json({accounts: accounts}); ^ TypeError: undefined is not a function 代替res.json时,我收到同样的错误:

res.send(accounts)

这是我的代码:

res.send({accounts: accounts}); ^ TypeError: undefined is not a function

var public_token = "";
var access_token = "";
var accounts = [];

};`

另外,当我运行最后两行时:

app.post('/authenticate', function (req, res) { console.log('post'); public_token = req.body.public_token; console.log(public_token); console.log('plaid: ' + app.client); server.client.exchangeToken(public_token, function (err, res) { console.log('exchange'); if (err) { //Handle Error console.log('exchange-error'); } else { //We now have exchanged our Plaid access token. //Store it somewhere persistent //Access token is used to make API calls access_token = res.access_token; console.log('access_token: ' + access_token); server.client.getAuthUser(access_token, function (err, res) { if (err != null) { //handle error console.log('authorization-error'); } else { // Our response will hold an array of accounts for this user, containing account names, // balances, account and routing numbers. accounts = JSON.stringify(res.accounts); console.log('accounts: ' + accounts); //Return account data res.json({accounts: accounts}); } }); } }); res.contentType('application/json'); res.send(accounts); });

帐户变量的默认值为 res.contentType('application/json'); res.send(accounts);

的初始值

我认为这可能是一个封闭问题,但我不确定。

1 个答案:

答案 0 :(得分:2)

 app.post('/authenticate', function (req, res) {
    console.log('post');
    public_token = req.body.public_token;
    console.log(public_token);
    console.log('plaid: ' + app.client);
    server.client.exchangeToken(public_token, function (err, ***res***) {

你在第二次回调中覆盖了res