#node.js
#node.js
Вопрос:
Итак, я снова начал изучать NodeJS. Я хотел использовать классный учебник, который я нашел. Однако это выдает ошибку?
в app.js У меня есть
require("dotenv").config();
const express = require("express");
const { loadClient, listEvents, createEvent } = require("./apiClient");
const app = express();
const port = 3000;
loadClient();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
// Make a GET request to return a list of events in JSON
app.get("/lijst", function(req, res) {
listEvents((events) => res.json(events));
});
// Make a POST request to create a new event in the calendar
app.post("/create", (req, res) => {
createEvent((event) => {
res.json(event);
});
});
app.listen(port, () =>
console.log(`Example app listening at http://localhost:${port}`)
);
module.exports = router;
ApiClient:
const { google } = require("googleapis");
const token = process.env.REFRESH_TOKEN;
const client_id = process.env.CLIENT_ID;
const client_secret = process.env.CLIENT_SECRET;
const redirect_url = "localhost:3000";
const loadClient = () => {
const auth = new google.auth.OAuth2(client_id, client_secret, redirect_url);
auth.setCredentials({ refresh_token: token });
google.options({ auth });
};
const makeApiCall = () => {
const calendar = google.calendar({ version: "v3" });
};
const getEvents = (instance, event, callback) => {
const calendarId = "primary";
const query = {
resource: {
timeMin: event.start.dateTime,
timeMax: event.end.dateTime,
items: [{ id: calendarId }],
},
};
// Return a list of events
instance.freebusy
.query(query)
.then((response) => {
const { data } = response;
const { calendars } = data;
const { busy } = calendars[calendarId];
callback(null, busy);
})
.catch((err) => {
callback(err, null);
});
};
const listEvents = (callback) => {
const calendar = google.calendar({ version: "v3" });
calendar.events.list(
{
calendarId: "primary",
timeMin: new Date().toISOString(), // Look for events from now onwards
maxResults: 10, // Limit to 10 events
singleEvents: true,
orderBy: "startTime",
},
(err, res) => {
if (err) return console.log("The API returned an error: " err);
const events = res.data.items;
callback(events);
}
);
};
const createEvent = (callback) => {
// Instance of calendar
const calendar = google.calendar({ version: "v3" });
// Start date set to next day 3PM
const startTime = new Date();
startTime.setDate(startTime.getDate() 1);
startTime.setHours(15, 0, 0, 0);
// End time set 1 hour after start time
const endTime = new Date(startTime.getTime());
endTime.setMinutes(startTime.getMinutes() 60);
const newEvent = {
calendarId: "primary",
resource: {
start: {
dateTime: startTime.toISOString(),
},
end: {
dateTime: endTime.toISOString(),
},
},
};
calendar.events.insert(newEvent, (err, event) => {
if (err) console.log(err);
callback(event.data.htmlLink);
});
};
ЖУРНАЛ ОШИБОК/
C:UsersgebruikerDesktophellomyExpressApproutesindex.js:9
loadClient();
^
TypeError: loadClient is not a function
at Object.<anonymous> (C:UsersgebruikerDesktophellomyExpressApproutesindex.js:9:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:UsersgebruikerDesktophellomyExpressAppapp.js:7:19)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
Комментарии:
1.
apiClient
ничего не экспортирует.2. Я вижу, но если я добавлю export ApiClient, он выдает неожиданный токен ошибки?
3. Я добавил: module.exports = loadClient; module.exports = getEvents; module.exports = CreateEvent; в ApiClient все та же ошибка?
4. можете ли вы попробовать
module.exports = loadClient
,module.getEvents = getEvents
,module.createEvent = createEvent
Ответ №1:
вы должны экспортировать функции, вы можете сделать так, добавьте эти строки, добавьте конец apiCLient
:
exports.loadClient = loadClient
exports.makeApiCall = makeApiCall
exports.getEvents = getEvents
exports.listEvents = listEvents
exports.createEvent = createEvent
или
module.exports ={
loadClient : loadClient,
makeApiCall : makeApiCall,
getEvents : getEvents,
listEvents : listEvents,
createEvent : createEvent
}