Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
like image 382
Manu Ram V Avatar asked Aug 08 '17 19:08

Manu Ram V


People also ask

How do I fix 403 unauthorized error in Postman?

The simple answer is; “You need to be given the correct access”. Without being given the correct access you'd technically be hacking the server, as it is specifically set up to restrict said access.

How do you handle a 403 error in React?

If 403 is returned, it means the user is logged in, but still not allowed access. He should first log out and then log in as a different user.

Why do I get an HTTP 403 Forbidden error when connecting to my API gateway APIs from a VPC?

The HTTP 403 Forbidden error most commonly occurs when private DNS is enabled for an API Gateway interface VPC endpoint that's associated with a VPC. In this scenario, all requests from the VPC to API Gateway APIs resolve to that interface VPC endpoint.


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));
like image 50
Pauli Avatar answered Oct 27 '22 22:10

Pauli


Probably CORS problem. Regular web pages can send and receive data from remote servers, but they're limited by the same origin policy. Extensions like postman aren't. You have to configure CORS on your backend.

like image 31
mradziwon Avatar answered Oct 27 '22 23:10

mradziwon


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));
like image 22
Sujith S Avatar answered Oct 27 '22 22:10

Sujith S


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.

like image 1
Clinton Jones Avatar answered Oct 27 '22 23:10

Clinton Jones