我正在学习https://www.woolha.com/tutorials/node-js-google-cloud-pub-sub-basic-examples的教程,但遇到了一些困难..
我在server.js中有以下代码:
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
dotenv.config(); // Reads the .env file from the local folder.
// PubSub constant initialisation
const PubSub = require(`@google-cloud/pubsub`);
const pubsub = new PubSub();
const data = new Date().toString();
const dataBuffer = Buffer.from(data);
const topicName = 'sensehat-led-config';
app.use(bodyParser.urlencoded({ extended: true}));
// Tell the app to use the public folder.
app.use(express.static('public'));
app.get('/', (req,res) => {
res.send('Hello from App Engine!');
})
app.get('/submit', (req, res) => {
res.sendFile(path.join(__dirname, '/views/form.html'));
})
// Need to figure out how to get the css file to work in this. Can't be that hard.
app.get('/sensehat', (req, res) => {
res.sendFile(path.join(__dirname, '/views/sensehat.html'));
})
app.get('/sensehat-publish-message', (req, res) =>{
pubsub
.topic(topicName)
.publisher()
.publish(dataBuffer)
.then(messageId => {
console.log(`Message ${messageId} published`);
})
.catch(err => {
console.error('ERROR:', err);
});
})
app.post('/submit', (req, res) => {
console.log({
name: req.body.name,
message: req.body.message
});
res.send('Thanks for your message!');
})
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log('Server listening on port ${PORT}...');
})但是当我运行它时,我得到一个'500 Server Error',并且查看Stackdriver日志,我得到以下错误:-
TypeError: PubSub is not a constructor at Object.<anonymous>
我绝对是NodeJS的新手,正在摸索我的路。在仔细阅读之后,我认为这个问题来自于
const PubSub = require(`@google-cloud/pubsub`);
const pubsub = new PubSub();线,但不知道如何纠正这一点。
发布于 2020-02-09 20:17:10
您需要默认导出@google-cloud/pubsub,但查找内容不在默认导出中。
将导入PubSub的方式更改为:
const {PubSub} = require(`@google-cloud/pubsub`);而不是:
const PubSub = require(`@google-cloud/pubsub`);发布于 2020-02-10 14:16:02
您可以尝试使用所有库的最新版本。package.json中的依赖项
"dependencies": {
"@google-cloud/pubsub": "1.5.0",
"google-gax": "1.14.1",
"googleapis": "47.0.0"
}示例代码:
const {
PubSub
} = require('@google-cloud/pubsub');
const pubsub = new PubSub({
projectId: process.env.PROJECT_ID
});
module.exports = {
publishToTopic: function(topicName, data) {
return pubsub.topic(topicName).publish(Buffer.from(JSON.stringify(data)));
},
};调用文件代码
const PubSubPublish = require('path to your above file')
let publishResult = await PubSubPublish.publishToTopic(process.env.TOPIC_NAME, data)希望它能帮上忙!
https://stackoverflow.com/questions/60136446
复制相似问题