reactjs - React & Socket - 使用 API 获取用户 ID
问题描述
我用 Socket 做了一个简单的聊天应用程序。我想用 API 从我的 Django 服务器“http://localhost:8000/api/current_user/”获取当前用户的 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,
required: true,
minLength: 1,
},
user: {
type: String,
required: true,
}
});
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
}
解决方案
推荐阅读
- .net-core - How can I implement batching in FSharp.Data.GraphQL?
- subdomain - 在主域在别处时创建一个 Github Pages 子域
- reactjs - Forked a react tutorial repo from github and after npm install found 1 critical issue among others. Just ignore or run npm audit fix?
- android - how to add views in onBindViewHolder?
- gimp - Gimp scriptfu 程序名称 Colors->Map->Rotate Colors
- javascript - MVC FormAction Bootstrap 模态确认
- r - 使用base R从另一个基于单独列中的值的条件值的表中删除行
- java - How to set an offset to AWT Image or Swing ImageIcon?
- docusignapi - DocuSign 隐式代码授予访问令牌无法从浏览器 url 部分读取?
- c# - C# WinFrom ComboBox SelectedValueChanged 事件触发延迟