Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST Request Using fetch() Returns 204 No Content

I'm making a POST request to a node.js server and I'm having trouble getting it to work. Here's my request:

const headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'this-can-be-anything',
};

export const postVote = (id, vote) =>
  fetch(`${uri}/posts/${id}`, {
    method: 'POST',
    headers,
    body: JSON.stringify({options: vote}),
  }).then(response => response.json())
    .then(data => data)
    .catch(err => console.log(err));

The function accepts an 'id' and a 'vote', both strings. The id is being used as part of the URI in the request, and the vote is being supplied as options so the API knows what to do with it. Both of the arguments are being passed correctly:

id = '8xf0y6ziyjabvozdd253nd'
vote = 'upVote'

Here's a link to the GitHub repository for the server/API:

Udacity Readable API

and a screenshot of the network when firing the request:

enter image description here enter image description here

UPDATE: Added the second screenshot which shows status 200. Though it shows this and appears to have been successful, it still doesn't post to the server and the information stays the same.

like image 725
Jacob Lockett Avatar asked Jan 28 '23 18:01

Jacob Lockett


1 Answers

What you are looking at is the OPTIONS request in the network tab. For cross origin requests, every request if preceeded by an OPTIONS request which tells the calling client (browser, for example) if those HTTP methods are supported by the remote server for use in crosss origin context.

Check the other requests out. If the OPTIONS request was responded to correctly by the server, the browser must automatically follow up with your POST request

EDIT: Also, the docs specify the param name to be option whereas in your screenshot it is coming up as options.

Further reading: CORS

like image 69
Chirag Ravindra Avatar answered Jan 31 '23 07:01

Chirag Ravindra