Fixing my POST Request to JSON Server

Entering my second code review I had everything sorted out except well… my POST request. The requirement was to persist data with a local json server while POSTing data to it. On my application I had a comment form to submit text to the local json server.

Original Code:

import React, { Component } from ‘react’class CommentForm extends Component {handleSubmit = (e) => {e.preventDefault();console.log(“submitted”);const body =;fetch(“http://localhost:3000/comments", {method: “POST”,body: JSON.stringify(body)}).then((response) => {console.log(response);return response.json(); // do something with response JSON});};render() {return (<div><h1>What is your favorite breed?</h1><form onSubmit={this.handleSubmit}><label>Answer: </label><br /><textarea type=”text” name=”body” /><br /><input type=”submit” /></form></div>);}}export default CommentForm

However with this code, I kept returning a 404 error. Why?

A 404 means that the server can’t find the resource you’re requesting. A connection is getting established to whatever is running on port 3000 (otherwise you’d get a response code in the 500's), but what is running there doesn’t know what /comments is using an HTTP POST request.

This doesn’t make sense to me because when I check my json server in my terminal it tells me that my URL is http://localhost:3000/comments

json-server --watch db.json

After a lot of trial and error, I realized I could just change the port I was running on. I changed it to 3001 and made a small change to the JSON.stringify argument and got it working.

fetch(“ http://localhost:3001/comments", {method: “POST”,body: JSON.stringify({comment: “text”})}).then((response) => {console.log(response)return response.json()})}