首页 > 解决方案 > 使用 React 和 CometChat 构建实时聊天小部件

问题描述

我正在尝试将第三方聊天 api cometchat 集成到我的项目中。我基本上需要以编程方式发送带有包含我的 appId 和 apiKey 的标头的 http 请求,以在聊天中创建我的应用用户。我的应用程序使用 mongodb 存储用户信息和 jwt 进行身份验证。但是每当我通过反应前端发送请求时,它都会返回错误 401,而不是返回用于聊天的令牌。

import express from "express";
import axios from "axios";
import authenticate from "../middlewares/authenticate";
const router = express.Router();
const User = require('../models/User');

const appID = "********";
const apiKey = "************";

const url = 'https://api.cometchat.com/v1';

const headers = {
  'Content-Type': 'application/json',
  appid: appID,
  apikey: apiKey,

};

router.get('/create',authenticate, (req, res) => {
  const data = {
    uid: req.currentUser.id,
    name: req.currentUser.name
  };

  axios.post(`${url}/users`, JSON.stringify(data), {
      headers,
    })
    .then(response => {
      requestAuthToken(response.data.data.uid)
        .then(token => {
          console.log('Success:' + JSON.stringify(token));
          res.json(token);
        })
        .catch(error => console.error('Error:', error));
    })
    .catch(error => console.error('Error:', error));
});

router.get('/auth', (req, res) => {
  const uid = req.query.uid;
  requestAuthToken(uid)
    .then(token => {
      console.log('Success:' + JSON.stringify(token));
      res.json(token);
    })
    .catch(error => console.error('Error:', error));
});

const requestAuthToken = uid => {
  return new Promise((resolve, reject) => {
    axios.post(`${url}/users/${uid}/auth_tokens`, null, {
        headers,
      })
      .then(response => {
        console.log('New Auth Token:', response.data);
        resolve(response.data.data);
      })
      .catch(error => reject(error));
  });
};

export default router;

在上面的代码中,“currentUser”是想要发起聊天的登录用户,“authenticate”中间件有助于提取用户信息。

发送服务器请求后,请参阅下面的服务器错误消息:

错误:{ 错误:getaddrinfo ENOTFOUND api.cometchat.com api.cometchat.com:443 at errnoException (dns.js:50:10) at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26) 代码:' ENOTFOUND',errno:'ENOTFOUND',系统调用:'getaddrinfo',主机名:'api.cometchat.com',主机:'api.cometchat.com',端口:443,配置:{ url:' https://api .cometchat.com/v1/users/undefined/auth_tokens ',方法:'post',数据:null,标题:{ 接受:'application/json,text/plain,/ ','Content-Type':'application/ json', appid: '*************', apikey: '**********************', '用户代理': 'axios/0.19.0' },

请参阅下面的 React 前端错误:

New message incoming! ffffff
ClientChat.js:139 Message sending failed with error: 

标签: expresschatcometchat

解决方案


推荐阅读