我正在使用Next.js-13.1并对我的数据库mongoDB进行API调用,以获取一些数据并在屏幕上显示它。在进行调用时,我收到了这个wierd错误,我古辛这是因为axios或我的数据库连接
我得到的错误
我的数据库连接代码bdConnect.js
import mongoose from "mongoose";
const connection = {};
async function dbConnect() {
if (connection.isConnected) {
return;
}
mongoose.set("strictQuery", false);
const db = await mongoose.connect(process.env.MONGO_URI)
console.log("Database Hot!!");
connection.isConnected = db.connections[0].readyState;
}
export default dbConnect;
我的getStudent API调用getStudent.js
import dbConnect from "../../utils/dbConnection";
import student from '../../models/student'
import jwt from 'jsonwebtoken';
dbConnect()
export default async function (req, res) {
try {
const { cookies } = req;
const token = cookies.ourSiteJwt;
if (!token) {
return res.json({ message: "Invalid token!" });
}
const { email } = jwt.decode(token)
const user = await student.find({ email })
if (user) {
const student = user[0]
return res.json({ student })
}
} catch (e) {
console.log(e);
}
return res.json({ "mess": "dail" })
}
我的页面,我想把我的数据从数据库StudentDetails.jsx
提取
"use client";
import axios from "axios";
import { useState } from "react";
import { Tablets } from "../global/Tablet";
export function StudentDetails({}) {
const [number, setNumber] = useState("");
const [email, setEmail] = useState("");
const [personalEmail, setPersonalEmail] = useState("");
const [dob, setDob] = useState("");
const [blood, setBlood] = useState("");
const [addmission, setAddmission] = useState("");
const [local, setLocal] = useState("");
const [permanent, setPermanent] = useState("");
async function handleStudent() {
try {
const res = await axios.get("http://localhost:3000/api/getStudent");
setNumber(res["data"]["student"]["contact"]);
setEmail(res["data"]["student"]["email"]);
setPersonalEmail(res["data"]["student"]["personalEmail"]);
setDob(res["data"]["student"]["dob"]);
setBlood(res["data"]["student"]["bloodGroup"]);
setAddmission(res["data"]["student"]["admissionType"]);
setLocal(res["data"]["student"]["localAddress"]);
setPermanent(res["data"]["student"]["permanentAddress"]);
} catch (e) {
console.log(e);
}
}
handleStudent();
return (
<div className="flex flex-col space-y-10 text-center">
<div className="flex flex-row space-x-10">
<Tablets content={number} label="Phone-Number" />
<Tablets content={email} label="College-Email" />
<Tablets content={personalEmail} label="Personal-Email" />
<Tablets content={dob} label="DOB" />
</div>
<div className="flex flex-row space-x-10">
<Tablets content={blood} label="Blood-Group" />
<Tablets content={addmission} label="Admission-Type" />
<Tablets content={local} label="Local-Address" />
<Tablets content={permanent} label="Permanent-Address" />
</div>
</div>
);
}
1条答案
按热度按时间nx7onnlm1#
在Next.js中从服务器端发出
axios
请求时,需要传递整个URL,而不仅仅是路由路径(/api/getStudent
),因为服务器不知道服务器上的当前URL是什么。确保在服务器端axios调用中使用完整的URL(http://localhost:3000/api/getStudent
)(并将3000
替换为运行Next.js应用程序的端口)