I'm practicing fetch api and have problem with posting data... in first step I post to 'http://localhost:3003/users' and it works fine -> code:
(async () => {
const res = await fetch('http://localhost:3003/users', {
method: 'POST',
body: JSON.stringify({ name, password }),
headers: {
'Content-Type': 'application/json'
}
});
but in another component (second step) I have this code:
useEffect(() => {
(async () => {
try {
const resp = await fetch(`http://localhost:3003/users/${userID}`, {
method: 'POST',
body: JSON.stringify({ tasks: [1, 2, 3] }),
headers: {
'Content-Type': 'application/json'
}
}).then(res => console.log(res));
} catch (err) {
console.error(err);
}
})();
}, [userID]);
and after logging to the console, got this:
Response {type: "cors", url: "http://localhost:3003/users/0", redirected: false, status: 404, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 404
statusText: "Not Found"
type: "cors"
url: "http://localhost:3003/users/0"
But when I go to http://localhost:3003/users/0, I can see the user so it seems that url works... Of course when I delete ${userID} it works, but array is added as the last object, not to this specific user... What's more - http://localhost:3003/users/${userID} works with GET method.
The question is - how to post data to single object in array in JSON server??
db.json:
{
"users": [
{
"id": 0,
"name": "Ola",
"password": "12345"
},
{
"name": "newuser",
"password": "newuser",
"id": 1
}
]
}
form submission checks if there is a user with this name; if not, post new user