首页 > 解决方案 > 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
}

标签: reactjssocket.iomern

解决方案


推荐阅读