Json-server: Server error 500 on POST

Created on 8 Jun 2018  路  4Comments  路  Source: typicode/json-server

Hi, I am having issues with POST method in my React-Redux app. GET works perfectly fine.

Error in Chrome devtools: POST https://my-json-server.typicode.com/casvil/recipes/recipes 500 (). Uncaught (in promise) SyntaxError: Unexpected token T in JSON at position 0

Error in Postman: TypeError: Cannot read property 'id' of undefined
at Function.createId (/app/node_modules/json-server/lib/server/mixins.js:46:39)
at Function.insert (/app/node_modules/lodash-id/src/index.js:47:49)
at /app/node_modules/lodash/lodash.js:4379:28
at arrayReduce (/app/node_modules/lodash/lodash.js:704:21)
at baseWrapperValue (/app/node_modules/lodash/lodash.js:4378:14)
at LodashWrapper.wrapperValue (/app/node_modules/lodash/lodash.js:9067:14)
at create (/app/node_modules/json-server/lib/server/router/plural.js:226:50)
at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
at next (/app/node_modules/express/lib/router/route.js:137:13)
at next (/app/node_modules/express/lib/router/route.js:131:14)

This is the fetch request:

export const createRecipe = (recipeData) => dispatch => {
    fetch('https://my-json-server.typicode.com/casvil/recipes/recipes', {
      method: 'POST',
      headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(recipeData)
  })
    .then(res => res.json())
    .then(recipe => dispatch({
      type: NEW_RECIPE,
      payload: recipe
    }));
}

db.json:

{
  "recipes": [
    {
      "name": "Tortillicas fatas",
      "difficulty": "2/5"
    },
    {
      "name": "Croquetas de pollo",
      "difficulty": "3/5"
    }
  ]
}

If I use instead your Posts json-server, the POST method works fine. https://jsonplaceholder.typicode.com/posts.

Is it possible that my db.json file is wrong, might have any wrong character?

Thanks!

Most helpful comment

The db.json file needs an "id" property

All 4 comments

The db.json file needs an "id" property

thank you!!

Thank you

just wanted to clarify here that the ids are auto-assigned on post requests sent to json-server, but any data that you've added to db.json yourself needs to have an id property with an integer value.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AdamCook44 picture AdamCook44  路  3Comments

dotmobo picture dotmobo  路  4Comments

Rutvik17 picture Rutvik17  路  4Comments

shikaan picture shikaan  路  3Comments

boydenhartog picture boydenhartog  路  3Comments