I
I
ionik_12021-07-27 11:23:42
Node.js
ionik_1, 2021-07-27 11:23:42

How to fix Cannot convert undefined or null to object error?

I'm trying to understand microservices, and how they communicate on this post

. I did everything the same, except for mongo, I just substituted id 1. When I send a request testq:9000/market/buy/1, I get an error in market.js Cannot convert undefined or null to object ?

gateway

const Gateway = require('micromq/gateway');

const gateway = new Gateway({
    microservices: ['market'],
    rabbit: {
        url: "amqp://localhost:5672",
    },
});

gateway.get('/market/buy/:id', (req, res) => res.delegate('market'));
gateway.get('/market', (req, res) => res.delegate('market'));

gateway.listen(9000);


notifications

const MicroMQ = require('micromq');
const WebSocket = require('ws');

// создаем микросервис
const app = new MicroMQ({
    name: 'notifications',
    rabbit: {
        url: "amqp://localhost:5672",
    },
});

// поднимаем сервер для принятия запросов по сокетам
const ws = new WebSocket.Server({
    port: 9001
});

// здесь будем хранить клиентов
const clients = new Map();

// ловим событие коннекта
ws.on('connection', (connection) => {
    // ловим все входящие сообщения
    connection.on('message', (message) => {
        // парсим сообщение, чтобы извлечь оттуда тип события и параметры.
        // не забудьте в продакшене добавить try/catch, когда будете парсить json!
        const { event, data } = JSON.parse(message);
        ws.clients.forEach(clients => {
            console.log(clients.send(console.log(message)))
        })
        // на событие 'authorize' сохраняем коннект пользователя и связываем его с айди
        if (event === 'authorize' && data.userId) {
            // сохраняем коннект и связываем его с айди пользователя
            clients.set(data.userId, connection);
        }
    });
});

// не забудьте реализовать удаление клиента после дисконнекта,
// иначе получите утечку памяти!
ws.on('close', function close() {
    console.log('disconnected');
});

// создаем действие notify, которое могут вызывать другие микросервисы
app.action('notify', (meta,res) => {
    // если нет айди пользователя или текста, тогда возвращаем статус 400
    if (!meta.userId || !meta.text) {
        res.status(400)
        res.json({error: 'Bad'})
        // return [400, { error: 'Bad data' }];
    }

    // получаем коннект конкретного пользователя
    const connection = clients.get(meta.userId);

    // если не удалось найти коннект, тогда возвращаем статус 404
    if (!connection) {
        return [404, { error: 'User not found' }];
    }

    connection.send(console.log('ТЕКС'));

    res.json({ ok: true})

});

app.start();


market

const MicroMQ = require('micromq');
const Items = new Object();
Items.id = 1

const app = new MicroMQ({
    name: 'market',
    rabbit: {
        url: "amqp://localhost:5672",
    },
});

app.get('/market/buy/:id',async (req, res) => {
    const { id } = req.params;

    req.app.ask('notifications', {
        server: {
            action: 'notify',
            meta: {
                userId: Items.id,
                text: JSON.stringify({
                    event: 'notification',
                    data: {
                        text: `Item #${id} was sold!`,
                    },
                }),
            },
        },
    }).catch(err => console.log('error', err));

    res.json({
        ok: true,
    });
});

app.start();



60ffc1c47c431717086384.jpeg

I can’t understand why it can’t convert, I pass an object to the ask query, and not null or undefined. It's been a week now and I can't fix it, please help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-07-27
@Alexandroppolus

Open node_modules/micromq/src/MicroService.js, add console.log on lines 36 and 74, print the values ​​of the variables. Or even try to use a debugger. In general, the code is open source, you can figure it out in a couple of hours.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question