res.json不能在callback函数里面工作
我目前正在开发一个API端点。
将数据发布到端点/authenticate
,我使用plaidClient.getAuthUser
函数获取用户的帐户信息,然后尝试使用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.send(accounts)
而不是res.json时,我收到相同的错误:
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); });
};`
另外,当我运行最后2行:
res.contentType('application/json'); res.send(accounts);
账户variables默认回到它的初始值[]
我认为这可能是一个封闭的问题,但我不知道。
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***) {
你在第二次callback中覆盖了水库
- Nodejs http://test.dev:3000/api/profile。 没有'Access-Control-Allow-Origin'标题Origin'http:// localhost:9000'
- 将数据从UDP套接字转发到HTTP服务器Node.js
- 使用Mongoose中间件从arrays级联删除钩子
- 想知道使用基于快速渲染variables的把手部分的最佳方法
- 使用mocha / chai来确保REST API提供一个文件?
- 使用JSHint和Express.js /'delete'(保留字)
- TypeError:undefined不是node.js / express.js中的函数
- 更清晰的node.jscallback
- 可以直接在req.body中的数据上工作吗?