"в файле nextmessanger \ src \ app \ api \ contertavations \ route.js может возникнуть проблема с логикой для обработки запроса сообщения. Это также может быть проблемой с полезной нагрузкой или где -то иначе, как и после запроса, он возвращает: < /p>
TypeError: The "payload" argument must be of type object. Received null
at POST (file://D%3A/ph/OneDrive/%D0%A0%D0%BE%D0%B1%D0%BE%D1%87%D0%B8%D0%B9%20%D1%81%D1%82%D1%96%D0%BB/Love/untitled19/NextMessanger/src/app/api/conversations/route.js:75:16)
73 | return NextResponse.json(newConversation);
74 | } catch (error) {
> 75 | console.error(error); // Log the error for debugging
| ^
76 | return new NextResponse('Internal Error', { status: 500 });
77 | }
78 | } {
code: 'ERR_INVALID_ARG_TYPE'
< /code>
И ничего не создается в базе данных MongoDB. < /p>
import { getCurrentUser } from "../../../../actions/getCurrantUser";
import { NextResponse } from "next/server";
import prisma from '../../../../libe/prismadb'
export async function POST(request) {
try {
const currentUser = await getCurrentUser();
const body = await request.json();
const {
userId,
isGroup,
members,
name
} = body;
if (!currentUser?.id || !currentUser?.email) {
return new NextResponse('Unauthorized', { status: 401 });
}
if (isGroup && (!members || members.length < 2 || !name)) {
return new NextResponse('Internal data', { status: 400 });
}
if (isGroup) {
const newConversation = await prisma.conversation.create({
data: {
name,
isGroup,
users: {
connect: [
...members.map((member) => ({
id: member.value
})),
{ id: currentUser.id }
]
}
},
include: {
users: true
}
});
return NextResponse.json(newConversation);
}
const existingConversations = await prisma.conversation.findMany({
where: {
OR: [
{ userIds: { equals: [currentUser.id, userId] } },
{ userIds: { equals: [userId, currentUser.id] } }
]
}
});
const singleConversation = existingConversations[0];
if (singleConversation) {
return NextResponse.json(singleConversation);
}
const newConversation = await prisma.conversation.create({
data: {
users: {
connect: [
{ id: currentUser.id },
{ id: userId }
]
}
}
});
return NextResponse.json(newConversation);
} catch (error) {
console.error(error); // Log the error for debugging
return new NextResponse('Internal Error', { status: 500 });
}
}
< /code>
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String?
email String? @unique
emailVerified DateTime?
image String?
hashedPassword String?
createdAt DateTime @default(now())
updateAt DateTime @default(now())
conversationIds String[] @db.ObjectId
conversation Conversation[] @relation(fields: [conversationIds], references: [id])
seenMassageIds String[] @db.ObjectId
seenMessages Message[] @relation("Seen", fields: [seenMassageIds], references: [id])
accounts Account[]
messages Message[]
}
model Account {
id String @id @default(auto()) @map("_id") @db.ObjectId
userId String @db.ObjectId
type String
provider String
providerAcountId String
refresh_token String? @db.String
access_token String? @db.String
expires_at Int?
token_type String?
score String?
id_token String? @db.String
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAcountId])
}
model Conversation {
id String @id @default(auto()) @map("_id") @db.ObjectId
createdAt DateTime @default(now())
lastMessageAt DateTime @default(now())
name String
isGroup Boolean
messagesIds String[] @db.ObjectId
message Message[]
userIds String[] @db.ObjectId
user User[] @relation(fields: [userIds], references: [id])
}
model Message {
id String @id @default(auto()) @map("_id") @db.ObjectId
body String?
image String?
createdAt DateTime @default(now())
seenIds String[] @db.ObjectId
user User[] @relation("Seen", fields: [seenIds], references: [id])
conversationId String[] @db.ObjectId
conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
senderIds String @db.ObjectId
sender User @relation(fields: [senderIds], references: [id], onDelete: Cascade)
}
< /code>
'use client'
import Image from "next/image";
import noPhotoPic from '../sideBar/360_F_186293166_P4yk3uXQBDapbDFlR17ivpM6B1ux0fHG.jpg'
import { useRouter } from 'next/navigation';
import {useCallback, useState} from "react";
import axios from "axios";
export default function Message({ lastMessage, photo, name , find , data}) {
const router = useRouter();
const getTime = () => {
const date = new Date();
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${hours}:${minutes}`;
};
const [isLoading, setIsLoading] = useState(false);
const handleClick = useCallback(() => {
setIsLoading(true);
axios.post('/api/conversations', { userId: data.id }, {
headers: { 'Content-Type': 'application/json' }
})
.then((response) => {
router.push(`/conversations/${response.data.id}`);
})
.catch((error) => {
console.error('Error creating conversations:', error);
})
.finally(() => setIsLoading(false));
}, [data, router]);
return (
{name}
{!find &&
{getTime()}
}
{!find && lastMessage }
{find && '=>'}
);
}
< /code>
I've tried a lot of logging, but nothing has helped. I will leave a link to my GitHub project and a link to the project from which I am taking the idea.
my - https://github.com/SashaChun/NextMessanger
I am taking the idea - https://github.com/AntonioErdeljac/mess ... ree/master
Подробнее здесь: https://stackoverflow.com/questions/794 ... api-conver
Я не могу правильно отправить запрос на сообщение по адресу http: // localhost: 3001/api/разговоры. Возвращает ошибку 50 ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение