NodeJS 服务器不使用whatsapp-web.js通过Express.js发送消息

pu3pd22g  于 2023-06-29  发布在  Node.js
关注(0)|答案(2)|浏览(136)

当我用手机确认QR码时,我的控制台上会打印“READY”,但当我向“/sendmessage”部分发送JSON请求时,我会收到“404”错误。同样,我在“/getqr”中得到“404”。我不知道我到底在哪里犯了一个错误,在whatsapp-web.js文档中写着我应该使用“LocalAuth”。由于我使用多个设备,我从文档中看到了如何这样做,但我找不到解决方案。我是Express.js的新手,我正在学习,如果你能帮助我,我会很高兴。

const express = require('express');
const createError = require('http-errors');
const morgan = require('morgan');
const fs = require('fs');
const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal')
require('dotenv').config();

const SESSION_FILE_PATH = './session.json';
let sessionCfg;
if (fs.existsSync(SESSION_FILE_PATH)) {
  sessionCfg = require(SESSION_FILE_PATH);
}

const client = new Client({
  authStrategy: new LocalAuth({
    clientId: "client-one"
  }),
  puppeteer: {
    headless: false,
  }
});

client.initialize();

client.on('qr', qr => {
  console.log('QR RECEIVED', qr);
  qrcode.generate(qr, { small: true });
  app.get('/getqr', (req, res, next) => {
    res.send({ qr });
  });
});

client.on('authenticated', (session) => {
  console.log('WHATSAPP WEB => Authenticated');
});

client.on('auth_failure', msg => {
  console.error('AUTHENTICATION FAILURE', msg);
});

client.on('ready', () => {
  console.log('READY');
});


const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(morgan('dev'));

app.post('/sendmessage', async (req, res, next) => {
  try {
    const { number, message } = req.body; // Get the body
    const msg = await client.sendMessage(`${number}@c.us`, message); // Send the message
    res.send({ msg }); // Send the response
  } catch (error) {
    next(error);
  }
});

app.use((req, res, next) => {
  next(createError.NotFound());
});

app.use((err, req, res, next) => {
  res.status(err.status || 500);
  res.send({
    status: err.status || 500,
    message: err.message,
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`🚀 @ http://localhost:${PORT}`));

bvk5enib

bvk5enib1#

编辑:当我用GET发送请求时,它可以工作,但是当我用POST发送时,我得到一个404错误。

eyh26e7m

eyh26e7m2#

我解决了这个问题,我以GET而不是POST的方式发送请求:(

相关问题