I am playing with some react code and trying out json-server. I wrote this code to have some simple logic to create notes with titles and store it in db. To mimic rest api I used json-server. But something doesn't work for me. When I post a new note through curl or httpie it works. But when I use this form in my app below, it adds the new note but the note is empty (it has only id), without content and title. What am I missing here?
The code is:
import { useState } from "react";
export default function () {
const [title, setTitle] = useState('title');
const [content, setContent] = useState('content here');
const [errorMessage, setErrorMessage] = useState('');
let handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
try {
let res = await fetch("http://localhost:3001/notes", {
method: "post",
body: JSON.stringify({
title: title,
content: content,
})
})
let resJson = await res.json();
console.log(resJson);
if (res.status == 201) {
setTitle('')
setContent('')
} else {
setErrorMessage(`something went wrong, ${res.status}`)
}
} catch(err) {
console.log(err);
}
}
return (
<form onSubmit={handleSubmit}>
<div className="flex flex-col">
<input
type="text"
value={title}
onChange={e => setTitle(e.target.value)}
className="border-2 border-gray"/>
<textarea
className="border-2 border-gray"
value={content}
onChange={(event) => setContent(event.target.value)}
autoFocus rows={5} wrap="soft"/>
<button type="submit">Add</button>
{errorMessage && <p>{errorMessage}</p>}
</div>
</form>
);
}
I run json-server like this:
json-server --watch db.json --port 3001
The curl (http) command works fine:
http post localhost:3001/notes --raw '{ "title": "A", "content": "B" }'
Or:
http post localhost:3001/notes title="test" content="test content"
Because when I display all notes I can see the content sent there:
http localhost:3001/notes
[
{
"content": "test content",
"id": 11,
"title": "test"
},
{
"content": "B",
"id": 15,
"title": "A"
}
]
But when I use my app, all that is added to the db is:
{
"id": 16
}
What is missing here?
Maybe you are missing the headers
in your fetch request, which is necessary to specify the content type of the data you're sending. You need to set the Content-Type
header to application/json
for the server to correctly understand the request payload.
let res = await fetch("http://localhost:3001/notes", {
method: "post",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: title,
content: content,
})
})