Home > database >  Create POST Request using JS
Create POST Request using JS

Time:11-28

I want to send a POST request to my backend from my website. But I get following error: blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

My Code

const response = await fetch("http://172.18.6.249:8090/test", {
          method: 'POST',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
          },
          body: `{
 "Id": 78912,
 "Customer": "Jason Sweet",
 "Quantity": 1,
 "Price": 18.00
}`,
      });

      response.json().then(data => {
          console.log(data);
      });

The server doesn't use any kind of authentication at the moment.

How can I avoid the error?

CodePudding user response:

CORS policy is very important and part of security.
In your case if you want to ignore CORS then you may use this : mode : "no-cors" in fetch Api

If this problem still persists then this CORS policy are registered on your backend. So, you are not able to hit request from your IP address.

below is front-end code example :

const response = await fetch("http://172.18.6.249:8090/test", {
          method: 'POST',
          mode : "no-cors",
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
          },
          body: `{
               "Id": 78912,
               "Customer": "Jason Sweet",
               "Quantity": 1,
               "Price": 18.00
          }`,
      });

      response.json().then(data => {
          console.log(data);
      }); 
  • Related