问题描述
我用 Socket 制作了一个简单的聊天应用程序。我想从我的 Django 服务器“http://localhost:8000/api/current_user/”中获取带有 API 的当前用户 ID
但是当我尝试以一种我不知道它不起作用的方式获取当前用户时。我该如何处理?我想我需要在客户端获取这个用户名并发送到服务器端。但我不知道该怎么做。
我看到了这个问题:How to send data to socket.io from react?
可能这就是我需要的,但我不知道如何使用它。我真的很困惑:(
import React,{ useState,useEffect } from "react";
const mongoose = require("mongoose");
const [username,setUsername] = useState([]);
const MessageSchema = mongoose.Schema({
date: {
type: Date,required: true,},content: {
type: String,minLength: 1,user: {
type: String,}
});
MessageSchema.statics.latest = (count) => {
return MessageModel.find({}).sort({"_id": "desc"}).limit(count);
}
MessageSchema.statics.create = (content) => {
useEffect(()=>{
fetch('http://localhost:8000/api/current_user/',{
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then(res => res.json())
.then(json => {
setUsername(json.id);
});
},[])
let msg = new MessageModel({
date: new Date(),content: content,user: username,});
return msg.save();
}
const MessageModel = mongoose.model("Message",MessageSchema);
module.exports = {
Schema: MessageSchema,Model: MessageModel
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)