I am using mongodb for my first time, I created a simple basic code that take a string input and store it in a database, but for some reason that didn’t work that easy as I expected, there is an error with the fetching path, I am giving it the path of the api so it can complete the saving process but the request is not send to the api, and of course I am sure that the path itself is right, this is the files structure:
app
api
route.js
page.jsx
models
mongodb.js
User.js
This is the page code:
"use client"
import Link from 'next/link'
import { useState } from "react"
export default function Home() {
const [input, setInput] = useState("")
const handleChange = (e) => {
setInput(e.target.value)
}
const handleSubmit = async (e) => {
e.preventDefault()
try {
const response = await fetch('/api/route', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: input }),
})
console.log('Response Status:', response.status)
const data = await response.json()
console.log('Response:', data)
} catch (error) {
console.log('Error1:', error)
}
}
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
<form onSubmit={handleSubmit}>
<input value={input} onChange={handleChange}/>
<button type="submit">Submit</button>
</form>
</div>
)
}
And these just for more details about the general code:
mongodb.js:
import mongoose from "mongoose"
require("dotenv").config();
async function connectToDatabase() {
try {
await mongoose.connect("mongodb://localhost:27017/mainDb");
console.log("Database connected");
} catch (error) {
console.error("Connection error", error);
}
}
export default connectToDatabase;
This is the User.js:
import mongoose from "mongoose"
const userSchema = new mongoose.Schema({
name: String,
)}
const User = new mongoose.model('User', userSchema);
export default User;
The route.js(api) code:
import { connectToDatabase } from '../../models/mongodb'
import { User } from '../../models/User'
export default async function Handler(req, res) {
console.log('API route hit')
if (req.method === 'POST') {
const { name } = req.body
try {
await connectToDatabase()
const newUser = new User({ name })
await newUser.save()
console.log('User added successfully', newUser)
res.status(201).json({ message: 'User added successfully', user: newUser })
} catch (error) {
console.log(error)
res.status(500).json({ message: 'Server error' })
}
} else {
res.status(405).json({ message: 'Method not allowed' })
}
}
Those are the errors in the console:
POST http://localhost:3000/api/route 404 (Not Found)
page.jsx:23 Response Status: 404
page.jsx:27 Error1:
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
The second error I do not know anything about what is causing it.
And I asked chatgpt but it didn’t know how to solve it for me.