如何使用nextjs和mongodb上传/创建数据
这里有人知道如何使用nextjs将数据上传到mongodb吗 我的代码有问题吗 原料药 我在获取数据方面没有任何问题。。。 但是当我尝试上传/发布我的数据时 主控台发帖http://localhost:3000/api/listing 400(错误请求) 正文:ReadableStream{locked:false} 页面如何使用nextjs和mongodb上传/创建数据,mongodb,api,next.js,Mongodb,Api,Next.js,这里有人知道如何使用nextjs将数据上传到mongodb吗 我的代码有问题吗 原料药 我在获取数据方面没有任何问题。。。 但是当我尝试上传/发布我的数据时 主控台发帖http://localhost:3000/api/listing 400(错误请求) 正文:ReadableStream{locked:false} 页面 import React,{useState}来自“React” 导出默认函数ListingUpload(){ const[title,setTitle]=useState(
import React,{useState}来自“React”
导出默认函数ListingUpload(){
const[title,setTitle]=useState(“”)
常量列表={title:title}
log(“原始数据:”,列表)
const upload=async()=>{
试一试{
const res=await fetch(“/api/listing”{
方法:“张贴”,
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”
},
正文:JSON.stringify(列表)
})
console.log(res)
日志(“正文:”,res.body)
}捕获(错误){console.log(错误)}
}
返回(
上传到mongodb
setTitle(e.target.value)}占位符=“放在这里”/>
提交
)
}
解析数据.create(请求正文)代码>非常危险。我可以在这里做任何我想做的事。然后检查
import { connectDB } from '../../util/mongodb';
export default async (req, res) => {
const { db } = await connectDB();
const { method } = req;
switch (method) {
case 'GET':
try {
const listings = await db
.collection("tests")
.find({})
.sort({ metacritic: -1 })
.toArray();
res.status(200).json({ success: true, data: listings });
} catch(error) {
res.status(400).json({ success: false });
}
break;
case 'POST':
try {
const listing = await db
.collection("tests")
.create(req.body);
res.status(201).json({ success: true, data: listing})
} catch(error){res.status(400).json({ success: false });}
break;
default:
res.status(400).json({ success: false });
break;
}
}
import React, { useState } from 'react'
export default function ListingUpload() {
const [title,setTitle]=useState('')
const listing = {title: title}
console.log("raw data :", listing)
const upload = async () => {
try {
const res = await fetch('/api/listing',{
method:"POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(listing)
})
console.log(res)
console.log("body :", res.body)
} catch (error) {console.log(error)}
}
return (
<div className="p-5">
<p>upload to mongodb</p>
<input type="text" value={title} label="title" onChange={(e) => setTitle(e.target.value)} placeholder="place here"/>
<button onClick={upload}>submit</button>
</div>
)
}