0

I am doing the React nanodegree that Udacity offers and am working on the second project, Readable. I have this code below that attempts to update a post with a new score.

 handleVote = (vote) => {
console.log(vote);
const url = `${process.env.REACT_APP_BACKEND}/posts/` + this.props.id;
fetch(url, { credentials: 'include', 
             option : "" + vote,
             headers: { 'Authorization': 'whatever-you-want' },  
             method: 'POST'
           } 
     ).then((response) => response.json()
     .then((json) => { console.log(json) })
     .catch((errors) => { console.log(errors); }));

}

I get a response back but it seems to have the same score. I'm not sure what I am doing wrong. I've tried adding the string as an option and also to the body. The "vote" is the string "upVote" or "downVote".

In the documentation they provide all they have this:

| `POST /posts/:id` | Used for voting on a post. | **option** - [String]: Either `"upVote"` or `"downVote"`. |

If anyone has done this project before I would love the help. I'm not really sure where to specify the "upVote" or "downVote" in the request.

  • It seems you need to send POST request with `Content-Type` as `application/x-www-form-urlencoded`, and make the request body as `option=upVote`. Please check https://github.com/ddavignon/Readable/blob/master/react-ui/src/actions/PostActions.js – shaochuancs Jan 03 '18 at 03:42

1 Answers1

0

In your API POST method, option:<option-value> pair needs to be specified as the body of the POST request, such as body: JSON.stringify({ option:${vote}}), instead of option : "" + vote,. See Request bodies can be set by passing body parameters. In this case, you also need to specify in the headers 'Content-Type': 'application/json' (in addition to 'Authorization': 'whatever-you-want') per this link, as @shaochuancs suggested.

Treefish Zhang
  • 1,131
  • 1
  • 15
  • 27
  • According to ddavignon's example code on GitHub, the `Content-Type` should be `application/x-www-form-urlencoded`. – shaochuancs Jan 03 '18 at 06:45
  • Thank you! It worked with adding 'Content-Type':application/x-www-form-urlencoded' but not with application/x-www-form-urlencoded. – SunLightGirl99 Jan 03 '18 at 12:32