我正在学习node.js。我正在尝试从index.js调用的模块中获取http响应
这是我的index.js:
const express = require("express");
const app = express();
const SheetData = require('./sheetdata.js');
app.post("/", function(request, response) {
// code
GoogleAuth.myGoogleAuth(JSON.parse(content), SheetData.mySheetData);
// code
}
这是我的模块:
exports.mySheetData = function () {
response.json({ user: 'tobi' })
}
我不断收到错误消息:
UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): TypeError: Cannot destructure property `data` of
'undefined' or 'null'
响应是否在模块范围内?是因为响应超出了范围,所以诺言被拒绝了吗?
谢谢
这是我的Google身份验证,来自node.js和google工作表教程。它仅用于身份验证。
const {google} = require('googleapis');
const fs = require('fs');
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
const TOKEN_PATH = 'token.json';
exports.myGoogleAuth = function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
console.log("inside google")
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return callback(err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
我的index.js是:
const express = require("express");
const app = express();
const SheetData = require('./sheetdata.js');
app.post("/", function(request, response) {
GoogleAuth.myGoogleAuth(JSON.parse(content), SheetData.mySheetData);
});
app.listen(process.env.PORT || 5000);
我的模块:
exports.mySheetData = function (auth) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: 'xxxxxxxxxxxxxx',
range: 'A2:R',
}, (err, {data}) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = data.values;
if (rows.length) {
response.json({ user: 'tobi' })
}}
我尝试将响应传递给模块: GoogleAuth.myGoogleAuth(JSON.parse(content),SheetData.mySheetData(response));
并在模块中:exports.mySheetData =函数(响应,身份验证){....
但不起作用。我收到错误消息:authClient.request不是一个函数