express - 使用 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:
解决方案
推荐阅读
- python - 如何在 Numpy 对象中处理 Numpy 对象?
- javascript - Javascript。ECIES方案如何有效存储Secp256k1私钥
- android - 如何解决 OnClick 的问题?
- python - 有没有办法让 index() 为重复项返回不同的索引?
- python - 如何将 pyarrow csv 文件转换为 python 字符串列表?
- python - Pandas:如何在 groupby 和 unstack 之后删除索引列?
- java - 用于选择下拉列表的第 5 个元素并检查重复元素是否存在于同一下拉列表中的硒逻辑
- javascript - 如何将张量转换为 Javascript 中的边界框坐标和标签?
- angular - 清晰数据网格内置过滤器不起作用
- javascript - 反应路由器链接不渲染组件