Fetch api post call returning 403 forbidden error in React js but the same URL working in postman

Viewed 40347

Below code is not working and returning 403 forbidden but the same url giving the correct response postman tool.

fetch('https://example.com/', {
  method: 'POST',
  headers: {'Content-Type': 'application/json', },
 body:JSON.stringify(sampledata),
}).then(result => console.log('success====:', result))
  .catch(error => console.log('error============:', error));
4 Answers

You need to add credentials: 'include' to your request.

fetch('https://example.com/', {
      credentials: 'include',
      method: 'POST',
      headers: {'Content-Type': 'application/json', },
      body: JSON.stringify(sampledata),

      }).then(result => console.log('success====:', result))
        .catch(error => console.log('error============:', error));

Please read this article Cross-Origin Resource Sharing , And change your API "Content-Type" to "text/plain". It will work (both fetch and axios)

fetch('https://example.com/', {
  method: 'POST',
  headers: {'Content-Type': 'text/plain', },
 body:JSON.stringify(sampledata),
}).then(result => console.log('success====:', result))
  .catch(error => console.log('error============:', error));

This is because Postman doesn't need to abide by access-control-allow-origin headers. Browser vendors look for this header from host server. If the server contains ACCESS-CONTROL-ALLOW-ORIGIN: "*" and Access-Control-Allow-Methods: "GET, POST, PUT, DELETE, OPTIONS" this would then tell the browser that this resource has given permission to be accessed.

Related