我正在尝试将第三方聊天API cometchat集成到我的项目中。我基本上需要以编程方式发送带有包含我的appId和apiKey的标头的http请求,以在聊天时创建我的应用程序用户。我的应用程序使用mongodb来存储用户信息和jwt进行身份验证。但是每当我通过React前端发送请求时,它都会返回错误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”是要发起聊天的登录用户,“身份验证”中间件有助于提取用户信息。
发送服务器请求后,请参阅下面的服务器错误消息:
错误:{错误:getaddrinfo ENOTFOUND api.cometchat.com api.cometchat.com:443在errnoException(dns.js:50:10) 在GetAddrInfoReqWrap.onlookup上(作为完成时)(dns.js:92:26) 代码:“ ENOTFOUND”, errno:“ ENOTFOUND”, syscall:“ getaddrinfo”, 主机名:“ api.cometchat.com”, 主持人:“ api.cometchat.com”, 端口:443, 配置: {url:'https://api.cometchat.com/v1/users/undefined/auth_tokens', 方法:“发布”, 数据:空, 标头: {接受:“ application / json,text / plain, / ”, 'Content-Type':'application / json', appid:“ *************”, apikey:“ **********************”, 'User-Agent':'axios / 0.19.0'},
请参见下面的React前端错误:
New message incoming! ffffff
ClientChat.js:139 Message sending failed with error: